【问题标题】:Microsoft asp c# RegEx escape multiple reserved charactersMicrosoft asp c# RegEx 转义多个保留字符
【发布时间】: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


    【解决方案1】:

    想想你正在生成什么作为一个表达式。您的示例正则表达式

    string ss = Regex.Escape("[") + Regex.Escape("^");
    

    相当于:

    string ss = @"\[\^";
    

    也就是说,它不是在寻找[ ^,而是在寻找[ 后跟 ^。所以ste[^ve 会匹配。

    如果要匹配任何包含一个或多个字符的字符串,则需要添加(非转义)括号来创建一组字符,例如:

    string ss = "[" + Regex.Escape("[") + Regex.Escape("^") + "]"
    

    也就是说,您要求正则表达式引擎在括号中的字符集中查找一个字符。

    【讨论】:

    • 请注意,Regex.Escape("-") 是“-”,因此您目前拥有的代码是很好的开始步骤,但不足以成为完整的答案。
    • @PMV 嘿,谢谢。为您的评论深入一点,我看到 Regex.Escape("[") 简单地等于“[”。所以有人会认为只使用“[”。这也失败了:'Regex reg = new Regex("[\"" + Regex.Escape("]") + "]"); string str = "s\"t[ev0e";'这失败了:'Regex reg = new Regex("[" + Regex.Escape("\"") + Regex.Escape("]") + "]");'这不是:'Regex reg = new Regex("[\"]");'我不是一个愚蠢的人,但这似乎有点不稳定。也许无常是一个更好的词。我正在研究一个数字或组合并建立一些测试。我可以看到我会得到我需要的。
    【解决方案2】:

    首先感谢@PMV。他的意见促使我进行了一系列测试。

    这显然是它真正的工作原理。

    无论我尝试什么,我都无法获得双引号或单引号来匹配,除非这两个单独测试。回到“C”语言,这实际上是有道理的。

    注意:在没有的情况下,您可以使用.Escape()。无论如何,IMO 必须使用函数为您创建 string = "\[" 只是愚蠢的。 .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));
    

    如此接近真棒。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 2019-11-02
      • 1970-01-01
      相关资源
      最近更新 更多