4

I'm using following regex to validate name:

^[a-zA-Z]{1}[a-zA-Z.' ]{1,20}$

Single quote is mentioned in the second range. However, when I validate a string against this regex, single quote (') invalidates the match. Here's my code:

let nameRegEx = "^[a-zA-Z]{1}[a-zA-Z.' ]{1,21}$"
let nameTest = NSPredicate(format:"SELF MATCHES %@", nameRegEx)
let isNameValid = nameTest.evaluate(with: name)

I've tried \' but no use.

HitMan
  • 175
  • 8
  • Are you sure `name` contains a `'` and not some `'`? If `let nameRegEx = "^[a-zA-Z][a-zA-Z0-9;#&.' ]{1,21}$"` works, then your string contains encoded text. Also note your regex matches at least 2 char strings, if you need to also match 1 char strings, replace `{1,21}` with `{0,21}`. – Wiktor Stribiżew Sep 19 '18 at 10:06
  • I'm comparing against `textField.text` property. Console shows regex as `"^[a-zA-Z]{1}[a-zA-Z.\' ]{1,21}$"` – HitMan Sep 19 '18 at 10:13
  • The problem is not with `nameRegEx`, but what `name` holds. – Wiktor Stribiżew Sep 19 '18 at 10:19
  • @WiktorStribiżew thanks for the clue. – HitMan Sep 19 '18 at 10:26

1 Answers1

6

Turns out textField.text returns and not '. Changing the character resolved the issue.

HitMan
  • 175
  • 8
  • 1
    This helped me and my team member (working on entirely different module). I still don't know why same key return 2 different characters. – HitMan Sep 19 '18 at 10:46
  • 1
    Check https://stackoverflow.com/a/31137195/3832970 answer. Looks like in your case, quotes got localized based on the current locale. – Wiktor Stribiżew Sep 19 '18 at 10:48