Regular Expression (regex) greedy mode, lazy mode use method, regular expression regex
Regular Expression greedy match mode, which is often prone to errors for beginners. Sometimes you need to match the content of a code segment and find that the matching is inconsistent with the desired content. It was found that it had something to do with the greedy mode. The following is an example:
What is greedy mode?
The strings include
1. start and end of h3, and "
2. Any character can appear in the middle. The number can be 0 or more. The regular expression can be :. *, ". "represents any character. The default mode does not match the line feed." * "duplicates the first character 0 or multiple.
3. The final result is as follows: "
The two results are the same. This is what we don't want to get. We want to start matching from the left and the first appearance
What is laziness?
Since the above several types indicate the number of repeated characters, the metacharacters are greedy by default. If we need a minimum length match, that is, the lazy mode, how do we write a regular expression? In fact, the common method in a regular expression is to add "?" to indicate repeated metacharacters "?" Character. The above regular expression can be written as: "
The lazy mode matches the string we need.
Conclusion: Regular Expression, which indicates the number of repeated string metacharacters ,'?, +, *, {} 'Will select greedy mode by default, and the maximum length will match the string. to switch to lazy mode, just add "?" You can switch to non-Greedy mode (lazy mode ).