I am trying to create a regex which can be used for a name.
static let nameRegex = try! NSRegularExpression(pattern: "^[a-zA-Z][A\\p{L}z'\\s]{0,19}$", options: [])
I am facing 2 issues:
[a-zA-Z] in the regex.I am trying to make it such that it should have a limit of 20 characters, should start with an alphabet, and should allow special characters to accept names such as : José, names with apostrophes too.
I am checking the regex like this:
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let textFieldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let filtered: [NSTextCheckingResult] = Constant.Regex.nameRegex.matches(in: textFieldText, options: [], range: NSMakeRange(0, textFieldText.count))
return filtered.count == 1
}
}
Any help will be appreciated!
You may use
"^(?!\\P{L})[\\p{L}'\\s]{0,20}$"
The pattern matches a string that fully matches the following patterns:
^ - start of string(?!\\P{L}) - a negative lookahead that fails the match if the next char is not a non-letter char (it requires a letter to the right of the current location or end of string)[\\p{L}'\\s]{0,20} - 0 to 20 letters, ' or whitespaces$ - end of string.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With