我正在使用foreach循环迭代.NET应用程序中的Regex匹配,如下所示:
foreach(Match m in Regex.Matches(input, pattern, options))
{
if(SomeNonRegExCondition(m))
continue; // no match
ProcessMatch(m);
}不幸的是,如果SomeNonRegExCondition(m)是true,那么模式匹配得太多了,我希望继续应用pattern at m.Index + 1而不是m.Index + m.Value.Length。.NET是否有一个选项可以这样做?
我不太确定一个附加的MVCE带来了什么,但是,有人要求:
// consider this a sample pattern and a sample condition
// changing the pattern to not match in the first place is no option for me
const string input = "(abc)abcxyz";
const string pattern = "ab.*yz";
foreach(Match match in Regex.Matches(input, pattern))
{
if ( /* some random condition, for MVCE using: */ match.Index == 1)
{
// Question: How to reset regex matcher in a way that it matches "abcxyz" at index 5
continue;
}
Console.WriteLine (match);
}发布于 2015-12-10 15:04:13
稍微切换一下方法,而不是从使用.Matches开始查找所有匹配,而是使用.Match查找第一个匹配,并使用.NextMatch迭代它们。
这样,在您的条件下,您可以通过再次调用.Match来重新启动匹配过程,从而完全更改match对象,方法是使用您必须使用的子字符串:
const string input = "(abc)abcxyz";
const string pattern = "ab.*yz";
var match = Regex.Match(input, pattern);
while(match.Success) {
if ( /* some random condition, for MVCE using: */ match.Index == 1)
{
//Start the matching process again at the next character, using Substring
match = Regex.Match(input.Substring(match.Index+1), pattern);
continue;
}
Console.Write(match); //abcxyz
match = match.NextMatch();
}https://stackoverflow.com/questions/34204762
复制相似问题