What is the difference between greedy mode and non-greedy mode in regular expressions
What is the difference between greedy and non-greedy patterns in regular expressions? I believe that many inexperienced people are at a loss about this, so this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
What is the greedy and non-greedy matching of regular expressions
Such as: String str= "abcaxc"
Patter p = "ab*c"
Greedy matching: regular expressions generally tend to maximum length matching, which is called greedy matching. As shown above, the pattern p matches the string str, and the result is a match to: abcaxc (ab*c).
Non-greedy matching: as long as the match gets the result, there are fewer matching characters. As shown above, the pattern p matches the string str, and the result is a match to: abc (ab*c).
Let's take a look at the greedy and non-greedy patterns of regular expressions through the example code, as shown below:
Greedy pattern: the largest part that can be matched
S = "This is a number 234,235-22-4223" r = re.match (. +) (\ dwells -\ d + ", s) r.groups () (" This is a number 23 "," 4-235-22-4223 ")
The greedy mode is that the + in ". +" will always find the last qualified character, so the first two numbers in the above code are not extracted.
Non-greedy mode: the fewer matches, the better.
S = "This is a number 234235-22-4223" r = re.match (r "(. +?) (\ This is a number-234-23522-4223", s) r.groups ()
The non-greedy mode is ". +?" It will stop when it matches the first character that meets the criteria.
After reading the above, have you mastered the difference between greedy mode and non-greedy mode in regular expressions? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!