Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for multiple words split by spaces

Tags:

regex

I am at the point where I am banging my head against my desk, to the amusement of my colleagues. I currently have the following regex

(^[\w](( \w+)|(\w*))*[\w]$)|(^\w$)

What I want it to do is match any string which contains only alphanumeric characters, no leading or trailing whitespace and no more than one space between words.

A word in this case is defined as one or more alphanumeric characters.

This matches most of what I want, however from testing it also thinks the second word onwards must be of 2 characters or more in length.

Tests:

ABC - Pass
Type 1 - Fail
Type A - Fail
Hello A - Fail
Hello Wo - Pass
H A B - Fail
H AB - Pass
AB H - Fail

Any ideas where I'm going wrong?

like image 906
Jon Taylor Avatar asked Dec 20 '22 08:12

Jon Taylor


1 Answers

Your regex is close. The cause of your two-character problem is here:

(^[\w](( \w+)|(\w*))*[\w]$)|(^\w$)
       right here ---^

After matching the group ( \w+), i.e. a space followed by one or more \w, which every word after the first must match because of the space, you then have another mandatory \w -- this is requiring the final word in the string to have two or more characters. Take that one out and it should be fine:

(^[\w](( \w+)|(\w*))*$)|(^\w$)

A simpler version would be:

^\w+( \w+)*$
like image 132
Reinstate Monica -- notmaynard Avatar answered Jan 01 '23 16:01

Reinstate Monica -- notmaynard