Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex issue for name field - Swift

Tags:

regex

swift

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:

  1. If I type apostrophe, it does not let me type anything further.
  2. I am unable to delete the first character on backspace in textfield because of [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!

like image 265
Mamta Avatar asked Dec 05 '25 11:12

Mamta


1 Answers

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.
like image 196
Wiktor Stribiżew Avatar answered Dec 08 '25 01:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!