Regular expression greedy matching pattern, for beginners, often prone to error. Sometimes you need to match a piece of code to find that the match is inconsistent with what you want. It turns out to be related to greedy patterns. As follows, let's look at the following example:
What is greedy mode
The string has: "
1, H3 the beginning and the end, "
2, the middle can appear any character, the number can be 0 or more, regular expression can be used:. *, "." Represents any character, the default mode does not match line wrapping, and "*" repeats the preceding character 0 or more.
3, finally we consider the result will be: "
2 kinds of results are the same, this is what we do not want, we want to start from the left, the first occurrence of
What is lazy mode
Since several of the above indicate the number of characters to repeat, the meta characters are by default greedy mode. If we need a minimum length match, which is lazy mode, how do we write regular expressions? In fact, the regular expression inside the general method is, in the expression of metacharacters characters, followed by a more "?" Characters can be. The above regular expression can be written as: "
Lazy mode, it matches up to the string we need.
Summary: Regular expressions, representing string repeats, '?, +,*,{} ' by default will select greedy mode, the maximum length matching string, and to switch to lazy mode, just in the meta character, followed by a "?" You can switch to non-greedy mode (lazy mode).