Can the order of regular expression matching be guaranteed in .NET? If I have a string:
+Apple+ +Orange+ +Banana+ +Foo+ +Bar+
+Second Line+ +More Stuff+
+Etc...+
Given the pattern (with global dot-all):
\+(.*?)\+
Does the RegEx class in .NET guarantee that the order of replacement for these items will be:
- Apple
- Orange
- Banana
- Foo
- Bar
- Second Line
- More Stuff
- Etc...
And is this order preserved if I'm using a replacement delegate to perfo开发者_运维问答rm my own replacing? i.e. Will the replacement delegate method get called in the order that each pattern match comes in, or can that not be guaranteed?
It seems that it is guaranteed. From Regex.Replace Method (String, MatchEvaluator)...
The method is equivalent to calling the Regex.Matches(String) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.
From Regex.Matches(String)...
The Matches method is similar to the Match method, except that it returns information about all the matches, instead of a single match, found in the input string. It is equivalent to the following code:
Match match = regex.Match(input);
while (match.Success) {
// Handle match here...
match = match.NextMatch();
}
Thus, it seems that each match will be passed to the MatchEvaluator delegate in order.
There are plenty of examples where the order of matches is used to pick a different replacement. C#, using a regular expression to find and replace certain characters in a word?
Could it change in a future version? It would likely break too many programs to make it worth it for Microsoft to change it, IMHO.
精彩评论