Reputation: 21
For name validation using the Regex, I need to have the below requirements.
I'm currently using this Regex:
(^[a-zA-Z' ]+(?:[- ][a-zA-Z']+)*$
This regex meets every requirement except the fact that it's allowing spaces before hyphen.
How can I disallow spaces before hyphen meeting every other requirement too here?
Upvotes: 2
Views: 44
Reputation: 785128
You may use this regex:
^ *[a-zA-Z']+(?:(?:-| +)[a-zA-Z']+)* *$
RegEx Breakup:
^
: Start *
: Match 0 or more leading spaces[a-zA-Z']+
: Match 1+ of letter or '
(?:
: Start non-capture group
(?:-| +)
: Match a -
or 1+ spaces[a-zA-Z']+
: Match 1+ of letter or '
)*
: End non-capture group. Repeat this group 0 or more times *
: Match 0 or more trailing spaces$
: EndUpvotes: 2
Reputation: 163287
You can exclude a space hyphen or hyphen space from matching.
Note that your pattern can also match just a space as the space is in the character class.
^(?!.*(?: -|- ))[a-zA-Z' ]+(?:[- ][a-zA-Z']+)*$
Upvotes: 1