3 回答
TA贡献1844条经验 获得超8个赞
进行三种不同的匹配,并使用程序中条件逻辑处理三种情况的组合。你不需要处理一个巨大的正则表达式中的所有东西。
编辑:让我扩大一点,因为问题变得更有趣:-)
您在此尝试捕获的一般想法是匹配某个正则表达式模式,但不是当测试字符串中存在某些其他(可能是任何数字)模式时。幸运的是,您可以利用您的编程语言:保持正则表达式简单,只需使用复合条件。最好的做法是在可重用的组件中捕获这个想法,所以让我们创建一个实现它的类和方法:
using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions;public class MatcherWithExceptions {
private string m_searchStr;
private Regex m_searchRegex;
private IEnumerable<Regex> m_exceptionRegexes;
public string SearchString {
get { return m_searchStr; }
set {
m_searchStr = value;
m_searchRegex = new Regex(value);
}
}
public string[] ExceptionStrings {
set { m_exceptionRegexes = from es in value select new Regex(es); }
}
public bool IsMatch(string testStr) {
return (
m_searchRegex.IsMatch(testStr)
&& !m_exceptionRegexes.Any(er => er.IsMatch(testStr))
);
}}public class App {
public static void Main() {
var mwe = new MatcherWithExceptions();
// Set up the matcher object.
mwe.SearchString = @"\b\d{5}\b";
mwe.ExceptionStrings = new string[] {
@"\.$"
, @"\(.*" + mwe.SearchString + @".*\)"
, @"if\(.*" + mwe.SearchString + @".*//endif"
};
var testStrs = new string[] {
"1." // False
, "11111." // False
, "(11111)" // False
, "if(11111//endif" // False
, "if(11111" // True
, "11111" // True
};
// Perform the tests.
foreach (var ts in testStrs) {
System.Console.WriteLine(mwe.IsMatch(ts));
}
}}所以上面,我们设置了搜索字符串(五位数),多个异常字符串(你的s1,s2和s3),然后尝试匹配几个测试字符串。打印结果应如每个测试字符串旁边的注释中所示。
TA贡献1859条经验 获得超6个赞
你的要求是,在所有情况下都不可能满足于parens。也就是说,如果你能以某种方式找到(左边和)右边的,它并不总是意味着你在内部。例如。
(....) + 55555 + (.....)-不,在括号内部竟然有(和)左,右
现在你可能会认为自己很聪明,(只有你)以前没有遇到过左边,反之亦然。这不适用于这种情况:
((.....) + 55555 + (.....))- 即使有关闭),(左边和右边,也在内部。
不可能发现你是否在使用正则表达式的parens中,因为正则表达式无法计算已经打开了多少个parens以及关闭了多少个parens。
考虑这个更简单的任务:使用正则表达式,找出字符串中的所有(可能是嵌套的)parens是否已关闭,这是(您需要查找的每一个)。你会发现它是不可能解决的,如果你用正则表达式无法解决这个问题,那么你无法弄清楚一个单词是否在所有情况下都在parens中,因为你无法弄清楚字符串中的某个位置所有前面(都有相应的)。
- 3 回答
- 0 关注
- 1478 浏览
添加回答
举报
