Reputation: 21
I am trying to write a javascript regular expression that matches a min and max number of words based on finding this pattern: any number of characters followed by a space. This matches one word followed by an empty space (for example: one ):
(^[a-zA-Z]+\s$)
When I add in the range quantifier {1,3}, it doesn't match two occurrences of the pattern (for example: one two ). What do I need to change to the regular expression to match a min and max of this pattern?
(^[a-zA-Z]+\s$){1,3}
Any explanation is greatly appreciated.
Upvotes: 0
Views: 930
Reputation: 6175
(^[a-zA-Z]+\s$)
will start scanning from the start of the line ^
, scan for a word [a-zA-Z]+
, scan for a space \s
, and expect the end of the line $
When you have two words, it does not find the end of the line, so it fails. If you take out $
, the second word would fail because it is not the start of the line.
So the start line and end line have to go around the limit scan.
To make it more generic:
(\S+\s*){1,3}
\S+
: At least one Non-whitespace
\s*
: Any amount of Whitespace
This will allow scanning of words even if there is no space at the end of the string. If you want to force the whole line, then you can put ^
in the front and $
at the end:
^(\S+\s*){1,3}$
Upvotes: 1
Reputation: 742
The following will work exactly as specified:
^([a-zA-Z]+ ){1,3}$
Replace the space with \s
to match any single whitespace character:
^([a-zA-Z]+\s){1,3}$
Add a quantifier to the \s
to set how many whitespace characters are acceptable. The following allows one or more by adding +
:
^([a-zA-Z]+\s+){1,3}$
If the whitespace at the end is optional, then the following will work:
^([a-zA-Z]+(\s[a-zA-Z]+){0,2})\s*$
Upvotes: 1