需要在C#中为以下请求编写RegEx。
输入 - 字符串,第1学期(否),第2学期(酒精)
我想知道,如果像“酒精”一样,在学期之前的最后2或3个单词中会出现“not”这样的词。
1. String : I am not taking alcohol these days.
回答 - 是
2. String : I am not feeling like taking alcohol these days.
答案 - 否
我尝试了类似下面的内容,但它不起作用:
Regex.IsMatch(textLine, @"(^|\s)" + negativeTerm + @"(\s|$)", RegexOptions.IgnoreCase)
答案 0 :(得分:0)
这个正则表达式应该可以胜任:
//var textLine = "I am not taking alcohol these days.";
var textLine = "I am not feeling like taking alcohol these days";
var negativeTerm = "not";
var searchedTerm = "Alcohol";
var matched = Regex.IsMatch(textLine, $@"\b{negativeTerm}\W+(?:\w+\W+){{1,2}}?{searchedTerm}\b", RegexOptions.IgnoreCase);