如何在 swift 中使用 “ 和 ' 单引号和双引号过滤?

How to use " and ' single quote and double quote filtering in swift?

提问人:Sanjug Sonowal 提问时间:8/7/2023 更新时间:8/7/2023 访问量:67

问:

我想做一个应该过滤掉特殊字符的函数。就像如果用户在文本区域上输入任何内容一样,如果他/她输入特殊字符,那么它将抛出并发出警报弹出窗口。现在它几乎适用于所有字符,除了单引号和双引号,我也想包括 [ “ 和 ' ]。谁能帮我解决这个问题。 非常感谢!!!

    func textViewDidChange(_ textView: UITextView) {
        guard var textViewText = textView.text else {
            return
        }
        var specialCharacterSet = CharacterSet(charactersIn: "₹!@#$%^&*()_+{}[]|<>?;=-")
        specialCharacterSet.insert(charactersIn: "'")
        

        if let range = textViewText.rangeOfCharacter(from: specialCharacterSet) {
            textViewText = textViewText.replacingCharacters(in: range, with: "")
            textView.text = textViewText

            let alertController = UIAlertController(title: "Error", message: "Special characters are not allowed!", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alertController, animated: true, completion: nil)
        }
    }
iOS Swift 字符串

评论

1赞 Larme 8/7/2023
specialCharacterSet.insert(charactersIn: "'\"")?但是你的问题是否与添加双引号有关,或者因为有“多个单引号和双引号”看起来很相似?喜欢等等?‘ « “ ´ »
0赞 vadian 8/7/2023
为避免对特殊字符进行转义,可以使用原始字符串语法#""#
0赞 Sanjug Sonowal 8/7/2023
我想要如果我输入 ' 或 “ 和所有其他特殊字符,那么它应该检查 textarea 是否有这个 ' 或 ” 如果有任何这个字符可用,警报应该显示,但现在单引号和双引号不起作用,其余的都在工作
0赞 Joakim Danielson 8/7/2023
也许使用您允许的字符的字符集会更容易/更清晰。

答:

0赞 Chandaboy 8/7/2023 #1

使用此方法,我也有共享屏幕截图以供参考(调试)

func setText()
{
    var textViewText = self.txtview?.text ?? ""
    let specialCharacterSet = CharacterSet(charactersIn: "₹!@#$%^&*()_+{}[]|<>?;=-'\"")
    
    if let range = textViewText.rangeOfCharacter(from: specialCharacterSet) {
        textViewText = textViewText.replacingCharacters(in: range, with: "")
        self.txtview?.text = textViewText
        
        let alertController = UIAlertController(title: "Error", message: "Special characters are not allowed!", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alertController, animated: true, completion: nil)
    }
}

enter image description here

enter image description here

enter image description here

enter image description here

评论

0赞 Sanjug Sonowal 8/7/2023
很抱歉,但这个不起作用
0赞 Chandaboy 8/7/2023
再次检查我的答案,我已经更新了它。
0赞 Sanjug Sonowal 8/10/2023
仍然不工作 (- -)
0赞 Chandaboy 8/10/2023
@SanjugSonowal您可以在 github 上共享代码,让我检查一下