需要.NET正则表达式转义哪些字符?字符、正则表达式、NET

2023-09-04 00:37:28 作者:终于笑醒

在一个.NET Regex被字面上的使用模式,特殊字符必须以转义是什么?

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

推荐答案

我不知道完整的字符集 - 但我不会依赖于知识,无论如何,我不会把它变成code。相反,我会用Regex.Escape每当我想要一些文字文本,我是不知道:

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);
}