Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Can't do regex matching in swift - iOS

Following is my code:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let prospectiveText = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)

        if prospectiveText.validateAsPerRegExpression(regExpression: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[]{}#%^*+=_\|~<>€£¥?-/:;()$&@".,?!'") == false {
            return false
        }

        return true
}

extension String {
    func validateAsPerRegExpression(regExpression: String) -> Bool {
        let floatExPredicate = NSPredicate(format:"SELF MATCHES %@", regExpression)
        return floatExPredicate.evaluate(with: self)
    }
}

Getting the following crash:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't do regex matching, reason: Can't open pattern U_REGEX_INVALID_RANGE (string e, pattern ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[]{}#%^*+=_|~<>€£¥?-/:;()$&@".,?!', case 0, canon 0)'

I think i'm forming regular expression in wrong way, Any idea on the fix?

Actually my intension is to avoid user to enter any other language input from keyboard, but all the keys in normal keyboard. If there is any better way to do it, please let me know. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is your regex. You need to escape the regex identifiers, otherwise, the compiler tries to make a formula out of them and fail. If you want to accept only English characters with special characters, use this

[A-Za-z0-9[]{}#%^*+=_|~<>€£¥?-/:;()$&@".,?!']

This only matches one character at a time. If you want to match one or more characters i.e entire string, use a +(one or more match) or *(zero or more match) at the end of the expression.

[A-Za-z0-9[]{}#%^*+=_|~<>€£¥?-/:;()$&@".,?!']+

This will match one or more characters (non-empty string). For future, you can use this website Regexr, this will verify your regex for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...