go to previous page   go to home page   go to next page



When to be Lazy

Regular Expression
Group 0
Group 1 Group 2 Group 3 Group 4

Lazy (reluctant) quantifiers are useful if you are using regular expressions to search a text for a pattern. For example, say that you are editing a text with a text editor that supports regular expression searches. (Many text editors do so, although they often support only basic regular expressions.) You wish to check that every beginning quote mark " is matched by a closing quote mark. So you search for this pattern:


Recall that the outer two quote marks in the above are delimiters and not part of the actual RE. The actual RE without delimiters is ".*"

Unfortunately, this will match any substring that starts with a " and ends with a " no matter what is inside. This is not what you want. If the line of text is

"balanced" quote marks have two " marks

the expression matches the substring

"balanced" quote marks have two "

since the greedy quantifier .* matches as much as it can, including the inner quote mark.


Fix the regular expression so that only "balanced" is matched.