查找所有出现的模式,无论它们是否重叠 [英] Find all occurrences of a pattern whether they overlap or not
本文介绍了查找所有出现的模式,无论它们是否重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的方法中有以下代码段:
I have this snippet in my method:
MatchCollection words = Regex.Matches("dog cat fun toy", @"\w\w\w.\w?");
foreach (Match match in words)
{
Console.WriteLine(match);
}
我希望看到这样的东西:
I expected to see something like this:
狗c
猫f
有趣的
dog c
cat f
fun t
但是程序提出了这样的建议:
But program came up with just that:
狗c
有趣的
dog c
fun t
据我所知,它跳过了第二次出现,因为它的一部分在上一次出现中.但是我仍然想看到它.我应该如何纠正我的代码段?
As I understood, it skipped second occurrence because part of it was in previous occurrence. But I still want to see it. How should I correct my snippet?
推荐答案
您可以尝试类似的事情
var regX = new Regex(@"\w\w\w.\w?");
string pattern = "dog cat fun toy";
int i = 0;
while (i < pattern.Length)
{
var m = regX.Match(pattern, i);
if (!m.Success) break;
Console.WriteLine(m.Value);
i = m.Index + 1;
}
这篇关于查找所有出现的模式,无论它们是否重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文