官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 海阳市| 盈江县| 大连市| 剑阁县| 建昌县| 萨迦县| 禹城市| 锡林郭勒盟| 泰安市| 农安县| 旺苍县| 明星| 浙江省| 阳信县| 奉节县| 阿拉尔市| 许昌县| 盐亭县| 晋城| 桐城市| 郸城县| 平乐县| 年辖:市辖区| 兖州市| 新郑市| 新蔡县| 林州市| 邵阳县| 曲阜市| 安丘市| 宿州市| 湖口县| 余干县| 缙云县| 秦皇岛市| 安仁县| 牡丹江市| 当涂县| 酒泉市| 陆河县| 界首市|