2

I'm using this regex for some basic name validation

^[a-zA-Z][a-zA-Z]*([-' ][a-zA-Z][a-zA-Z]*)*$

However I'd like to also allow Mr & Mrs Bobble as valid. My current regex only allows a single space between character groups and I'm not sure how to allow <space>&<space> or <space>

BlueChippy
  • 5,935
  • 16
  • 81
  • 131

1 Answers1

2

You may use

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

See the regex demo

The non-capturing group (?: & |[-' ]) matches either a space, &, space or a -, ' or a single space. Non-capturing groups are used when the text they match won't be accessed after the match is found, so, in this case, all groups should be non-capturing: (?: & |[-' ]) groups two alternatives with the | alternation operator and (?:(?: & |[-' ])[a-zA-Z][a-zA-Z]*) groups a quantified sequence of patterns.

If you mean to match any whitespace, replace the literal spaces in the pattern with \s.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563