繁体   English   中英

如果不包含指定的关键字,则放弃匹配

[英]Discard match if it doesn't contain a specified keyword

示例文字:

START
This is example example example example example example example example .
END
START
This is example 1234 14 756 214 6456 5 2 4234 66 match.
END
START
This is This isThis isThis isThis isThis isThis isThis isThis is.
END

我只需要匹配“ START”和“ END”关键字之间的文本,并且其中包含单词“ match”。

我目前有这个正则表达式:

Regex.Matches(myString, @"START(.*?match.*?)END", RegexOptions.Singleline);

它无法正常工作,因为它会在匹配“ END”关键字之前等待“匹配”字词出现:

This is example example example example example example example example .
END
START
This is example 1234 14 756 214 6456 5 2 4234 66 match.

如果“ START”和“ END”关键字之间的句子不包含“ match”字样,该如何丢弃?

您需要防止正则表达式引擎越过匹配边界; 惰性量词不会这样做,但是负面的超前断言可以:

Regex.Matches(myString, @"START((?:(?!\bEND\b).)*match(?:(?!\bEND\b).)*)END", RegexOptions.Singleline);

在regex101.com上进行实时测试。

(?:(?!\\bEND\\b).)*与任何字符( . )匹配,但(?!\\bEND\\b)是它没有以END关键字(?!\\bEND\\b) 通过将其包含在重复的非捕获组(?:...)*我们可以确保在每个字符上都测试了此条件。

我得出了这个解决方案,它似乎比其他解决方案更简单。 它允许使用除单词END以外的任何字符(在这种情况下,还包括换行符,但这就是单行符的作用)

START((?!END).)*match((?!END).)*END

您确定要使用正则表达式执行此类任务吗? 您可以通过以下方法解决:

        string mystring = "START This is example example example example example example example example. END START This is example 1234 14 756 214 6456 5 2 4234 66 match. END START This is This isThis isThis isThis isThis isThis isThis isThis is. END";
        string result = "";

        foreach(string text in mystring.Split(new string[] { "START", "END" }, StringSplitOptions.RemoveEmptyEntries))
        {
            if (text.Trim().Contains("match"))
            {
                result = text;
            }
        }

暂无
暂无

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

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