Can any one help me to understand the difference between two approaches to regular expressions, with some suitable examples?
- greedy
- non-greedy
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Chekout http://www.regular-expressions.info/repeat.html.
Greediness refers to the quantity of times the regex engine will try to match certain set of characters. The way to state the “greediness” of a regex expression is using the special characters
*,+,?and{}.Consider
Matching these regex against str will result in:
r1 matching “asdfasdf b bbb” (non-greedy, tries to match b just once)
r2 matching “asdfasdf bbbb” (greedy, tries to match asdf as many times as possible)
r3 matching “asdfasdf bbb b” (non-greedy, matches b exactly 3 times)
r4 matching “asdfasdfbbbb“ (ULTRA-greedy, matches almost any character as many times as possible)
As regex are means to represent specific text patterns, it’s not like greediness it’s a matter of approach. You will sometimes need to match three times foo(
/(foo){3}/) or infinite times bar(/(bar)*/).