What characters need to be escaped in .NET Regex?

后端 未结 4 756
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 03:18

In a .NET Regex pattern, what special characters need to be escaped in order to be used literally?

4条回答
  •  粉色の甜心
    2020-12-15 03:41

    I don't know the complete set of characters - but I wouldn't rely on the knowledge anyway, and I wouldn't put it into code. Instead, I would use Regex.Escape whenever I wanted some literal text that I wasn't sure about:

    // Don't actually do this to check containment... it's just a little example.
    public bool RegexContains(string haystack, string needle)
    {
        Regex regex = new Regex("^.*" + Regex.Escape(needle) + ".*$");
        return regex.IsMatch(haystack);
    }
    

提交回复
热议问题