0

I am looking for a regular expression to use in Swift to validate cardholder name for a credit card. I am looking for a regEx which:

  • Has minimum 2 and maximum of 26 characters
  • Accept dashes (-) and apostrophes (') only and no other special character
  • Capital and small alphabets and no numbers.
  • Should not start with a blank space.

I was using this

"^[^-\\s][\\p{L}\\-'\\s]{2,26}$"

but it only accepts dash (-) no apostrophe (')

wp78de
  • 18,207
  • 7
  • 43
  • 71
Somya
  • 65
  • 1
  • 7

2 Answers2

4

try with this regex

(?<! )[-a-zA-Z' ]{2,26}

see here

https://regex101.com/r/0UVvR1/1

alsjflalasjf.dev
  • 1,589
  • 13
  • 11
  • This regex is not validating John Mc'Kenzie. It's not taking spaces between the first name last name as well. – Somya Apr 24 '18 at 02:43
  • *I am looking for a regEx which - - Has minimum 2 and maximum 26 characters - Accept dashes (-) and apostrophes (') only and no other special character - Capital and small alphabets and no numbers. - Should not start with a blank space*>>> you didn't ask for that... try now – alsjflalasjf.dev Apr 24 '18 at 02:53
  • Card holder name may also contain dots (.) like John F. Kennedy or Mrs. Robinson – heximal Dec 12 '18 at 14:21
  • OP explicitly asks for this `Has minimum 2 and maximum 26 characters - Accept dashes (-) and apostrophes (') only and no other special character`; so, she/he didn't want dots to be a valid char; but, sure, you can add dots too. – alsjflalasjf.dev Dec 12 '18 at 14:38
3

Guessing from your description, this is what you are looking for:

^[\p{L}'-][\p{L}' -]{1,25}$

Demo

A few remarks:

  • you propbably do not want to allow all possible white-space chars [\r\n\t\f\v ] but just spaces.
  • you have to adjust the allowed lenght of the second string if you add a 1st group that does not include space and dash (since that group contributs an additional character).
  • with \p{L} you allow any kind of letter from any language (which is good); otherwise use [a-zA-z] if just want to allow the regular (ASCII) alphabet.

PS: Do not forget to escape the pattern properly: "^[\\p{L}'][\\p{L}' -]{1,25}$"

wp78de
  • 18,207
  • 7
  • 43
  • 71