【发布时间】:2016-10-01 15:27:33
【问题描述】:
我只想使用正则表达式,如果字符串中存在的字符不是常规可键入字符,它将返回真/假。这应该是一件容易的事,不是吗?
我没有模式,我只是想知道是否存在任何不在列表中的字符。
在常规的 RegEx 世界中,我只是:
[^0-9a-zA-Z~`!@#$%\^ &*()_-+={\[}]|\\:;\"'<,>.?/] // <space> before the ampersand
...我知道有点臃肿,但这篇文章很重要...
我发现您无法转义多个保留字符。 例如, Regex ex = Regex.Escape("[") + Regex.Escape("^") 不会命中: "st[eve" 或 "st^ve"
如下失败:
string ss = Regex.Escape("[") + Regex.Escape("^");
Regex rx = new Regex(ss);
string s = "st^eve";
rx.IsMatch(s));
这些也一样:
string ss = Regex.Escape("[") + "[0-9]";
Regex rx = new Regex(ss);
string s1 = "st^eve"; rx.IsMatch(s1));
string s2 = "st^ev0e; rx.IsMatch(s2));
string s3 = "stev0e; rx.IsMatch(s3));
但这是唯一不会失败的 Microsoft c# Regex 转义字符:
string ss = Regex.Escape("^");
Regex rx = new Regex(ss);
string s = "st^eve"; rx.IsMatch(s));
除了对非转义字符的测试之外,我是否必须为每个需要转义的字符开发单独的测试?
这是其他人正在做的吗?
如果有更好的方法,我愿意接受想法?
感谢您的考虑。
【问题讨论】:
标签: c# asp.net regex string escaping