如何防止某些特殊关键字仅在文本字段中使用正则表达式?

问题描述 投票:0回答:2

我只是试图阻止一些特殊字符,其余的应该被允许。在以前的组件开发人员已经使用

replacingOccurrences
处理这些字符,但现在需求发生了变化,需要使用正则表达式来处理它。让我分享以前的代码。

extension YourNameViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
    return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
     let newInput = string
     newInput = newInput.replacingOccurrences(of: " ", with: "")
     newInput = newInput.replacingOccurrences(of: "^", with: "")
     newInput = newInput.replacingOccurrences(of: "'", with: "")
     newInput = newInput.replacingOccurrences(of: """, with: "")
    return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder();
    return true
}

}

我不确定如何使用正则表达式处理这 4 个字符。 请帮忙建议最好的处理方法。

ios swift regex uitextfielddelegate
2个回答
0
投票

一个解决方案是使用

replace
的 RegexComponent 版本:

newInput.replace(/[ ^'"]/, with: "")

确保

^
字符不是第一个在方括号内,因为它将具有匹配除其他字符以外的任何字符的特殊含义。

另一种是使用

option
replacingOccurrences
参数。

newInput = newInput.replacingOccurrences(of: "[ ^'\"]", with: "", options: .regularExpression)

请注意,在这种用法中,您必须使用反斜杠转义

"


0
投票

将此添加到项目中的任何位置

extension String {

    func replacingRegex(
        matching pattern: String,
        findingOptions: NSRegularExpression.Options = .caseInsensitive,
        replacingOptions: NSRegularExpression.MatchingOptions = [],
        with template: String
    ) throws -> String {

        let regex = try NSRegularExpression(pattern: pattern, options: findingOptions)
        let range = NSRange(startIndex..., in: self)
        return regex.stringByReplacingMatches(in: self, options: replacingOptions, range: range, withTemplate: template)
    }
 }

之后如何使用这个

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         var newInput = string
         do {
            newInput = try newInput.replacingRegex(matching: "[ ^'\"]", with: "")
        } catch {
            print(error.localizedDescription)
        }
        print(newInput)
        return true
    }
© www.soinside.com 2019 - 2024. All rights reserved.