我正在学习C#正则表达式,我正在尝试这个:
String pattern = @"\(([0-9]+ *, *)*[0-9]+\)";
Regex reg = new Regex(pattern);
if (!reg.IsMatch(TestGroupIDs))
throw new Exception("Invalid TestGroupIDs string in App.config. The proper format is: (4,6)");
Run Code Online (Sandbox Code Playgroud)
它应该验证任何字符串像这样:"(3)","(3,4,5)","(3 ,4)","(3 , 4)",等.
我对这个字符串进行了测试:"(4,6) OR 1=1"正则表达式匹配.在尝试了一些其他类似的案例后,我发现.NET Regex将该" OR 1=1"部分视为布尔表达式.这是.NET中的错误吗?任何解决方法?
鉴于人们不相信我,我将展示一些我尝试过的案例:
"(4,6) || 1 = 1" => A first chance exception of type 'System.NullReferenceException' occurred in DesktopMonitor.exe Incorrect syntax near '|'.
"(4,6) OR 1" => An expression of non-boolean type specified in a context where a condition is expected, near '1'.
我相信这些结果应该证实我的观点.
感谢@false和@Rawling纠正我.请参阅下面的@false的答案.带走:
我发现C#Regex将"OR 1 = 1"部分视为布尔表达式
不,它完全忽略了它.您正在检查您的正则表达式是否与字符串匹配:
(4,6) OR 1=1
Run Code Online (Sandbox Code Playgroud)
嗯,确实如此!就在这儿:
(4,6) OR 1=1
-----
Run Code Online (Sandbox Code Playgroud)
如果要验证字符串,通常需要将正则表达式锚定到字符串的开头和结尾 - 分别使用^和$- 因此它只能匹配整个字符串.
String pattern = @"^\(([0-9]+ *, *)*[0-9]+\)$";
Run Code Online (Sandbox Code Playgroud)