简体   繁体   中英

Javascript regular expression quantifier

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$)

Debuggex Demo

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}

Debuggex Demo

Any explanation is greatly appreciated.

Take ^ and $ out of the quantified group, because you can't match the beginning and end of the string multiple times in one line.

^([a-zA-Z]+\s){1,3}$

DEMO

(^[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}$

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*$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM