lbc1013
lbc1013

Reputation: 21

REGEX - Allowing multiple spaces and cannot have spaces before or after hyphen(-)

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']+)*$ 

(https://regexr.com/6umck)

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

Answers (2)

anubhava
anubhava

Reputation: 785128

You may use this regex:

^ *[a-zA-Z']+(?:(?:-| +)[a-zA-Z']+)* *$

RegEx Demo

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
  • $: End

Upvotes: 2

The fourth bird
The fourth bird

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']+)*$

Regex demo

Upvotes: 1

Related Questions