繁体   English   中英

正则表达式与C#中的交集匹配

[英]regex matches with intersection in C#

我想知道是否有可能获得所有匹配的MatchCollection,即使它们之间存在交集。

string input = "a a a";
Regex regex = new Regex("a a");
MatchCollection matches = regex.Matches(input);
Console.WriteLine(matches.Count);

此代码返回1,但我希望它返回2.如何实现它?
谢谢您的帮助。

string input = "a a a";
Regex regexObj = new Regex("a a");
Match matchObj = regexObj.Match(input);
while (matchObj.Success) {
    matchObj = regexObj.Match(input, matchObj.Index + 1); 
}

将迭代字符串,开始下一次迭代,在前一个匹配位置之后的一个字符,因此找到所有匹配。

您可以在while循环中将“aa”替换为“a”并将其与正则表达式再次匹配,直到没有匹配为止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM