What is the greedy feature of C # regular expression engine
This article focuses on "what is the greedy feature of C# regular expression engine". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the greedy feature of C# regular expression engine?"
The greedy feature of the C # regular expression engine that matches as many characters as possible as long as the pattern allows. You can change the matching pattern to non-greedy by adding "?" after the "repeat description character" (*, +). Look at the following example:
Code string x = "Live for nothing,die for something"; Regex R1 = new Regex (@ ". * thing"); if (r1.IsMatch (x)) {Console.WriteLine ("match:" + r1.Match (x) .value); / / output: Live for nothing,die for something} Regex R2 = new Regex (@ ". *? thing"); if (r2.IsMatch (x)) {Console.WriteLine ("match:" + r2.Match (x) .Value) / / output: Live for nothing}
Use "(? >...)" Method to make a non-retroactive declaration. Due to the greedy nature of the C# regular expression engine, in some cases, it will backtrack to get a match, as shown in the following example:
Code string x = "Live for nothing,die for something"; Regex R1 = new Regex (@ ". * thing,"); if (r1.IsMatch (x)) {Console.WriteLine ("match:" + r1.Match (x) .value); / / output: Live for nothing,} Regex R2 = new Regex (@ "(? >. *) thing,"); if (r2.IsMatch (x)) / / mismatch {Console.WriteLine ("match:" + r2.Match (x) .Value) }
In R1, because of its greedy nature, ". *" will match all the way to the * of the string, and then match "thing", but fail at ",", where the engine will backtrack and match successfully at "thing,".
In R2, the entire expression match failed because non-backtracking was enforced.
At this point, I believe you have a deeper understanding of "what is the greedy feature of the C# regular expression engine?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!