Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between greedy mode and non-greedy mode in regular expressions

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report