regex matches with intersection in C#

匿名 (未验证) 提交于 2019-12-03 00:48:01

问题:

I wonder if it is possible to get MatchCollection with all matches even if there's intersection among them.

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

This code returns 1, but I want it to return 2. How to achive it?
Thank you for your help.

回答1:

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);  } 

will iterate over the string starting the next iteration one character after the position of the previous match, therefore finding all matches.



回答2:

You can do it in a while loop by replacing "a a" by "a" and match it another time against the regex until there is no match.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!