Skip to main content
 首页 » 编程设计

c#之使用正则表达式检测“\”(反斜杠)

2024年01月18日39hnrainll

我有一个C#正则表达式

[\"\'\\/]+ 


如果要在字符串中找到某些特殊字符,我想用它来评估并返回错误。

我的测试字符串是:

\test 


我有一个对此方法的调用来验证字符串:

public static bool validateComments(string input, out string errorString) 
{ 
    errorString = null; 
    bool result; 
 
    result = !Regex.IsMatch(input, "[\"\'\\/]+");  // result is true if no match 
                                                   // return an error if match 
 
    if (result == false) 
        errorString = "Comments cannot contain quotes (double or single) or slashes."; 
 
    return result; 
} 


但是,我无法匹配反斜杠。我尝试了几种工具,例如regexpal和VS2012扩展,它们似乎都可以很好地匹配此regex,但是C#代码本身不行。我确实意识到C#正在将字符串从Javascript Ajax调用传入时转义,所以还有另一种匹配该字符串的方法吗?

它确实匹配/ test或'test或“ test,但不匹配\ test

请您参考如下方法:

\甚至由正则表达式使用。尝试"[\"\'\\\\/]+"(因此请对\进行两次转义)

请注意,您可能有@"[""'\\/]+“,也许它会更易读:-)(通过使用@,您必须转义的唯一字符是",而使用第二个"")

您实际上并不需要+,因为最后[...]的意思是“其中之一”,对您来说就足够了。

不要吃你无法咀嚼的东西...代替正则表达式使用

// result is true if no match 
result = input.IndexOfAny(new[] { '"', '\'', '\\', '/' }) == -1;   


我认为没有人会丢失工作,因为他更喜欢 IndexOf而不是正则表达式:-)