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?
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+)*$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With