Regular expressions 2. Quantifiers

Quantifiers specify how often the preceding regular expression should match.

* Try to match the preceding regular expression zero or more times.
    Example: "(ab)c*" matches "ab" followed by zero or more "c"s, i.e., "ab", "abc", "abcc", "abccc" ...
+ Try to match the preceding regular expression one or more times.
    Example: "(ab)c+" matches "ab" followed by one or more "c"s, i.e., "abc", "abcc", "abccc" ...
{m, n} Try to match the preceding regular expression between m and n times.
If you leave m out, it is assumed to be zero. If you leave n out it is assumed to be infinity. I.e., "{,n}" matches from zero to n times, "{m,}" matches a minimum of m times, "{,}" matches the same as "*" and "{n}" is shorthand for "{n, n"} and matches exactly n times.
    Example: "(ab){1,2}" matches "ab" and "abab".
? Try to match zero or one time.

Changing match behaviour

Default the quantifiers above try to match as much as possible, they are greedy. You can change greedy behaviour to lazy behaviour by adding an extra "?" after the quantifier.

    Example: In the string "cabddde", the search "abd{1,2}" matches "abdd", while the search for "abd{1,2}?" matches "abd".
    Example: In the string "cabddde", the search "abd+" matches "abddd", while the search for "abd+?" matches "abd".

Links to this page


© djmw, July 8, 2001