Case and Negation in JavaScript Regular Expressions
Welcome to the third part of a five-part series that examines the use of regular expressions in JavaScript. In this part, we'll look at the effects of case sensitivity, how to use negation, and more.
Case and Negation in JavaScript Regular Expressions - Matching Repetitions (Page 4 of 5 )
The quantifier metacharacters ?, * , + , and {} allow us to determine the number of repeats for a portion of a regexp we consider to be a match. Quantifiers are put immediately after the character, character class, or grouping (see later) that we want to specify. They have the following meanings:
a* : match 'a' 0 or more times, i.e., any number of times
a+ : match 'a' 1 or more times, i.e., at least once
a? : match 'a' 0 or 1 times
a{n,} : match at least n or more times
a{n} : match exactly n times
a{n,m} : match at least n times, but not more than m times.
Note: the letter "a" above stands for any character of a text, e.g. "b," "c," "d," "1," "2," etc.
Examples
*
The above symbol matches the preceding item 0 or more times. /o*/ matches 'o' in 'ghost' of the available string "A ghost booooed." It would also match "oooo" in the available string. To give the regexp more meaning, you have to combine it with other characters. For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled," but nothing in "A goat grunted", even though this last string has an 'o'.
+
The above symbol matches the preceding item one or more times. It is equivalent to {1,} - see below. /a+/ matches the 'a' in "candy" and all the "a"s in "caaaaaaandy."
?
This above symbol matches the preceding item 0 or one time. /e?le?/ matches the 'el' in "angel" and the 'le' in "angle." /e?le?/ means you have a word which has an "l" optionally preceded by "e" and optionally followed by "e." This means it will also match "lying." By the time you finish this series, you will know how to modify the regexp to restrict it to match only "angel" or "angle."
{n,}
Where n is a positive integer, the above matches at least n occurrences of the preceding item.
For example, /a{2,} doesn't match the 'a' in "candy", but matches all of the "a"s in "caandy" and in "caaaaaaandy."
{n}
The above matches exactly n occurrences of the preceding item, where n is a positive integer. /a{2}/ doesn't match the "a" in "candy," but it matches all of the "a"s in "caandy," and only the first two "a"s in "caaandy."
{n,m}
The above matches at least n and at most m occurrences of the preceding item, where both n and m are positive integers.
For example, /a{1,3}/ matches nothing in "cndy", the "a" in "candy," the first two "a"s in "caandy," and the first three "a"s in "caaaaaaandy." Notice that when matching "caaaaaaandy," the match is "aaa," even though the available string had more "a"s in it.