Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...