Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to match a maximum of 4 spaces

Tags:

regex

I have a regular expression to match a persons name.

So far I have ^([a-zA-Z\'\s]+)$ but id like to add a check to allow for a maximum of 4 spaces. How do I amend it to do this?

Edit: what i meant was 4 spaces anywhere in the string

like image 297
Razor Avatar asked Nov 28 '22 16:11

Razor


2 Answers

Don't attempt to regex validate a name. People are allowed to call themselves what ever they like. This can include ANY character. Just because you live somewhere that only uses English doesn't mean that all the people who use your system will have English names. We have even had to make the name field in our system Unicode. It is the only Unicode type in the database.

If you care, we actually split the name at " " and store each name part as a separate record, but we have some very specific requirements that mean this is a good idea.

PS. My step mum has 5 spaces in her name.

like image 144
pipTheGeek Avatar answered Mar 12 '23 06:03

pipTheGeek


^                    # Start of string
(?!\S*(?:\s\S*){5})  # Negative look-ahead for five spaces.
([a-zA-Z\'\s]+)$     # Original regex

Or in one line:

^(?!(?:\S*\s){5})([a-zA-Z\'\s]+)$

If there are five or more spaces in the string, five will be matched by the negative lookahead, and the whole match will fail. If there are four or less, the original regex will be matched.

like image 38
Markus Jarderot Avatar answered Mar 12 '23 06:03

Markus Jarderot