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

Viewed 30

For name validation using the Regex, I need to have the below requirements.

  • Can include letters, spaces, apostrophe(') and hyphen(-) only
  • multiple spaces are allowed between the characters (example: " asd asd asd asd ")
  • Cannot have spaces before or after hyphen(-) (example: "abc-abc" is allowed, "abc -abc" and "abc- abc" is not allowed)

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?

2 Answers

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

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

Related