- Java 9 Regular Expressions
- Anubhava Srivastava
- 292字
- 2021-07-02 18:58:35
Greedy versus reluctant (lazy) matching using quantifiers
So far, we have discussed all the quantifiers available to us in a regular expression to match fixed-size or variable-length text. These quantifiers are, by default, greedy in nature. Greediness is in terms of their matching. In a regex, quantifiers attempt to match the longest possible text, from left to right. Only when the regex engine fails to complete a match, it moves back in the input text one character at a time, as required, to complete the match. Sometimes, the regex engine moves back and forth multiple times in attempts to complete a match in a complex (nested) regular expression.
So, for example, if the input is pqrstmprt and our regular expression is p.+r, then our match will be from p at the start to the last r, that is, pqrstmpr, not pqr. It is due to the same greediness that was stated earlier, where the regex engine attempts to match the longest possible match when using quantifiers.
Regular expressions also provide a way to change this greedy behavior of the regex engine. If we place a ? (called the lazy or reluctant quantifier) in front of any of the quantifiers, then the behavior of the regex engine changes from greedy to lazy. With the lazy quantifier in place, the regex engine attempts to match the shortest match, only expanding further as required to complete the match with the remainder of the regex pattern next to the lazy quantifier.
So, in the preceding example, if we use the regex as p.+?r, then our matched text will be pqr, because pqr is the smallest possible match between p and r.
Here is a list of all the greedy quantifiers and their corresponding lazy quantifiers:

- 微服務(wù)設(shè)計(第2版)
- Mastering NetBeans
- Java 9 Concurrency Cookbook(Second Edition)
- Delphi程序設(shè)計基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- Clojure for Domain:specific Languages
- 假如C語言是我發(fā)明的:講給孩子聽的大師編程課
- 編程數(shù)學(xué)
- Learning Unity 2D Game Development by Example
- Asynchronous Android Programming(Second Edition)
- 匯編語言編程基礎(chǔ):基于LoongArch
- 持續(xù)集成與持續(xù)交付實(shí)戰(zhàn):用Jenkins、Travis CI和CircleCI構(gòu)建和發(fā)布大規(guī)模高質(zhì)量軟件
- Django實(shí)戰(zhàn):Python Web典型模塊與項目開發(fā)
- Mastering Adobe Captivate 7
- Android Development Tools for Eclipse
- 零基礎(chǔ)學(xué)Scratch 3.0編程