This time I will bring you a detailed explanation of the use of the regular lazy matching mode (?). What are the precautions when using the regular lazy matching mode (?). The following is a practical case, let's take a look.
Regular expressionLazy matching mode:
In the chapter on greedy matching mode, it has been said that human nature is greedy, hoping to get more money, status and even beautiful women, but there are also Many stoic people only need to meet their basic life needs. There is also such a matching principle in regular expressions. Let’s introduce it below.
1. The concept of lazy mode:
This mode is just the opposite of greedy mode. It matches as few characters as possible to satisfy the regular expression, for example:
var str="axxyyzbdkb"; console.log(str.match(/a.*b/));
The above code is greedy mode, so it can match the entire string. Let’s modify it into lazy matching mode:
var str="axxyyzbdkb"; console.log(str.match(/a.*?b/));
The above code is lazy matching. The method is to add a question mark (?) after the repeated quantifier.
The lazy matching mode is to match as few characters as possible, but must meet the matching rules of the regular expression. For example, in the above code, * can repeatedly match 0 or more previous characters or subexpressions, but the regular expression The end of the formula must be b, so the regular expression can match axxyyzb in the above string.
The summary is as follows:
1. Add a question mark (?) after the repeated quantifier to form a lazy match.
2. Lazy matching will match as few characters as possible, but the entire matching pattern must be satisfied.
2. LazyQualifierList:
Semantic explanation | |
Can be repeated any number of times, but as few times as possible. | |
Can be repeated once or as many times as you like, but as few times as possible, but the minimum number is 1. | |
Can be repeated 0 or 1 times, but as few times as possible. | |
You can repeat n to m, but repeat as little as possible. The minimum number of matches is n. | |
can be repeated more than n times, but it should be repeated as little as possible, and at least n should be matched. |
The above is the detailed content of Detailed explanation of the use of regular lazy matching pattern (?). For more information, please follow other related articles on the PHP Chinese website!