提问人:Sanjug Sonowal 提问时间:8/7/2023 更新时间:8/7/2023 访问量:67
如何在 swift 中使用 “ 和 ' 单引号和双引号过滤?
How to use " and ' single quote and double quote filtering in swift?
问:
我想做一个应该过滤掉特殊字符的函数。就像如果用户在文本区域上输入任何内容一样,如果他/她输入特殊字符,那么它将抛出并发出警报弹出窗口。现在它几乎适用于所有字符,除了单引号和双引号,我也想包括 [ “ 和 ' ]。谁能帮我解决这个问题。 非常感谢!!!
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)
}
}
答:
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)
}
}
评论
0赞
Sanjug Sonowal
8/7/2023
很抱歉,但这个不起作用
0赞
Chandaboy
8/7/2023
再次检查我的答案,我已经更新了它。
0赞
Sanjug Sonowal
8/10/2023
仍然不工作 (- -)
0赞
Chandaboy
8/10/2023
@SanjugSonowal您可以在 github 上共享代码,让我检查一下
评论
specialCharacterSet.insert(charactersIn: "'\"")
?但是你的问题是否与添加双引号有关,或者因为有“多个单引号和双引号”看起来很相似?喜欢等等?‘ « “ ´ »
#"
"#