首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Regex匹配器集指标

Regex匹配器集指标
EN

Stack Overflow用户
提问于 2015-12-10 14:43:07
回答 1查看 175关注 0票数 0

我正在使用foreach循环迭代.NET应用程序中的Regex匹配,如下所示:

代码语言:javascript
运行
复制
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带来了什么,但是,有人要求:

代码语言:javascript
运行
复制
// 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);
}
EN

回答 1

Stack Overflow用户

发布于 2015-12-10 15:04:13

稍微切换一下方法,而不是从使用.Matches开始查找所有匹配,而是使用.Match查找第一个匹配,并使用.NextMatch迭代它们。

这样,在您的条件下,您可以通过再次调用.Match来重新启动匹配过程,从而完全更改match对象,方法是使用您必须使用的子字符串:

代码语言:javascript
运行
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34204762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档