Reputation: 2109
I'm struggling to find a regular expression that matches a name that can contain a space in it. So far this is what I've tried:
^(?![\s]+$)(?![\s]{2,})[a-zA-Z\s]{2,25}$
Unfortunately I'm not so good on regex. The name can contain only letters and optionally a space character, and if a space is present there must be no more than one space character in the word. The whole name length (counting also the space) must be between 2 and 25 characters long. Here some examples of names that have to match:
Here some examples of names that have not to match the regular expression:
The last requirement is that I have to use this regular expression both in javascript and php.
Thanks in advance!
Upvotes: 0
Views: 1526
Reputation: 110685
You could match the string with the following regular expression.
^(?!.* .* )[a-zA-Z ]{2,25}$
The elements of the expression are as follows.
^ # match beginning of string
(?!.* .* ) # negative lookahead asserts the string does not
# contain two (or more) spaces
[a-zA-Z ]{2,25} # match between 2 and 25 letters and spaces
$ # match end of string
Upvotes: 3
Reputation: 163362
The pattern ^(?![\s]+$)(?![\s]{2,})[a-zA-Z\s]{2,25}$
that you tried matches:
^(?![\s]+$)
(?![\s]{2,})
[a-zA-Z\s]{2,25}$
There is no restriction to match a single space
in the whole string
Note that \s
could also match a newline or a tab.
What you could do is assert 2-25 characters in the string.
Then match 1+ chars a-zA-Z and optionally match a single space and 1+ chars a-zA-Z
^(?=.{2,25}$)[a-zA-Z]+(?: [a-zA-Z]+)?$
The pattern matches:
^
Start of string(?=.{2,25}$)
Positive lookahead, assert 2-25 chars in the string[a-zA-Z]+
Match 1+ chars A-Za-z(?: [a-zA-Z]+)?
Optionally match
and again 1+ chars from the character class$
End of stringSee a regex demo.
Upvotes: 2