贪婪,不贪婪,在C#中的正则表达式的所有贪婪的匹配 [英] Greedy, Non-Greedy, All-Greedy Matching in C# Regex
本文介绍了贪婪,不贪婪,在C#中的正则表达式的所有贪婪的匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能在下面的例子中的所有比赛:
How can I get all the matches in the following example:
// Only "abcd" is matched
MatchCollection greedyMatches = Regex.Matches("abcd", @"ab.*");
// Only "ab" is matched
MatchCollection lazyMatches = Regex.Matches("abcd", @"ab.*?");
// How can I get all matches: "ab", "abc", "abcd"
感谢
彼得
PS:我想在所有的比赛一个通用的方式。上面的例子仅仅是一个例子。 : - )
P.S.: I want to have the all matches in a generic manner. The example above is just an example. :-)
推荐答案
您可以使用类似:
MatchCollection nonGreedyMatches = Regex.Matches("abcd", @"(((ab)c)d)");
这时你应该有三个反向引用与AB公司,ABC和ABCD。
Then you should have three backreferences with ab, abc and abcd.
不过,说实话,这样的正则表达式不会让太多的感觉,尤其是当它变大就变得不可读。
But, to be honest, this kind of regex doesn't makes too much sense, especially when it gets bigger it becomes unreadable.
< STRONG>编辑:
MatchCollection nonGreedyMatches = Regex.Matches("abcd", @"ab.?");
和你有一个的错误BTW。这只能匹配ab和美国广播公司(阅读:AB +任何(可选)字符
And you got an error there btw. This can only match ab and abc (read: ab + any (optional) character
懒版本:
MatchCollection greedyMatches = Regex.Matches("abcd", @"ab.*");
是:
MatchCollection nonGreedyMatches = Regex.Matches("abcd", @"ab.*?");
这篇关于贪婪,不贪婪,在C#中的正则表达式的所有贪婪的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文