Hướng dẫn php regex non greedy
I have a string (from a file):
How I get the string:
I want to match the overview line ( I tried .*\n, but that will match everything and then a new line. Is there a way to make regex non-greedy? I have tried: asked Feb 19, 2013 at 21:10
Chris MuenchChris Muench 17.9k69 gold badges204 silver badges352 bronze badges 3 Add To specifically match the line beginning with "Overview: ", use this regex:
The answered Feb 19, 2013 at 21:13
9 Summary: in this tutorial, you’ll learn about the regex non-greedy (or lazy) quantifiers that match their preceding elements as few times as possible. Introduction to the regex non-greedy (or lazy) quantifiersIn regular expressions, the quantifiers have two versions: greedy and non-greedy (or lazy). In the previous tutorial, you learned how greedy quantifiers work. To turn a greedy quantifier into a non-greedy quantifier, you can append a question mark (
The following example uses the non-greedy quantifier (
Output:
How the non-greedy quantifier (+? ) works. First, the regex engine searches for a match starting from the first position in the string. Because the regex engine cannot find a match, it continues searching until it finds the first quote ( Second, the regex engine finds a match for the rule Third, the regex engine repeats the first and second steps starting from the position after the first match and returns the next result: Finally, the regex engine continues to search till the end of the string: Summary
Did you find this tutorial useful? |