我只想使用正则表达式,如果字符存在于不是常规类型字符的字符串中,则返回true / false。这应该是一件容易的事,不应该吗?
我没有模式,前面,我只是想知道是否存在不在列表中的任何字符。
在常规的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));
我是否必须为每个逃避必需的字符开发一个单独的测试以补充对非转义字符的测试?
这是其他人在做什么吗?
如果有更好的方法,我愿意接受想法吗?
感谢您的考虑。
答案 0 :(得分:0)
想想你作为一个表达产生什么。您的示例RegEx
string ss = Regex.Escape("[") + Regex.Escape("^");
相当于:
string ss = @"\[\^";
也就是说,它不是在寻找[
或 ^
,它正在寻找[
,然后是 {{1} }。所以^
会匹配。
如果要匹配包含一个或多个字符的任何字符串,则需要添加(非转义)括号以创建一组字符,例如:
ste[^ve
也就是说,您要求正则表达式引擎在括号中的字符集中查找一个字符。
答案 1 :(得分:0)
首先感谢@PMV。他的输入促使我做了一堆测试。
这显然是如何运作的。
无论我尝试什么,我都无法获得双引号或单引号来匹配,除非那两个地方各自进行单独测试。这实际上是有道理的思考一直回到C&#39; C&#39;语言。
注意:在没有的情况下, 使用.Escape()
。 IMO必须使用函数来创建一个字符串=&#34; \ [&#34;对你来说无论如何都是愚蠢的。 .Escape() is not necessary on ^ nor { nor ] nor \ nor " nor '
。
string ss = "[0-9A-Z~`!@#$%^& *()-_+={[}]|\\:;<,>.?/";
// does not match ~ ss = ss + Regex.Escape("\"");
// does not match ~ ss = ss + Regex.Escape("\'");
ss = ss + "]";
Regex rx = new Regex(ss);
// rx = new Regex("[" + Regex.Escape("\"") + "]");
// works just as well as the line above ~ rx = new Regex("[\"]");
// rx = new Regex("[" + Regex.Escape("'") + "]");
rx = new Regex("[']");
string s = "ste've";
Console.WriteLine("search string {0}", ss);
Console.WriteLine("IsMatch {0}", rx.IsMatch(s));
如此接近令人敬畏。