正则表达式 Greedy Matching And Non-Greedy Matching

The usual rule for matching in REs is sometimes called “left-most longest“: when a pattern can be matched at more than one place within a string, the chosen match will be the one that starts at the earliest possible position within the string, and then extends as far as possible. Normally Perl pattern matching is greedy. By greedy, we mean that the parser tries to match as much as possible. In the string abcbcbcde, for example, the pattern
Greedy and non-greedy matching /(bc)+/ can match in six different ways as shown in the figure:

正则表达式 Greedy Matching And Non-Greedy Matching_第1张图片

In the above image, the third of these matched patterns is “left-most longest, ” also known as greedy. In some cases, however, it may be desirable to obtain a “left-most shortest” or minimal match. We can make a greedy matching into a non-greedy match using ‘?‘ at the end of RE i.e ‘*?‘ matches the smallest number of instances of the preceding subexpression that will allow the overall match to succeed. Similarly, ‘+?‘ matches at least one instance, but no more than necessary to allow the overall match to succeed, and ‘??‘ matches either zero or one instances, with a preference for zero.

正则表达式 Greedy Matching And Non-Greedy Matching_第2张图片

你可能感兴趣的:(正则表达式)