c#允许正则表达式中的斜杠(和其他类似字符)

Kem*_*min 1 .net c# regex asp.net

我正在尝试根据输入的字符验证字符串.我希望能够设置除字符和数字之外允许的字符.以下是我的扩展方法:

public static bool isAlphaNumeric(this string inputString, string allowedChars)
{
    StringBuilder str = new StringBuilder(allowedChars);
    str.Replace(" ", "\\s");
    str.Replace("\n","\\\\");
    str.Replace("/n", "////");
    allowedChars = str.ToString();

    Regex rg = new Regex(@"^[a-zA-Z0-9" + allowedChars + "]*$");
    return rg.IsMatch(inputString);
}
Run Code Online (Sandbox Code Playgroud)

我使用它的方式是:

s string = " te\m@as 1963' yili.??çöÖÇÜ/nda olbnrdu" // just a test string with no meaning
if (s.isAlphaNumeric("???ö\Ö@üÜçÇ ?'?/.")) {...}
Run Code Online (Sandbox Code Playgroud)

当然它给出了一个错误:

parsing "^[a-zA-Z0-9???ö\Ö@üÜçÇ\s?'?/.]*$" - Unrecognized escape sequence
Run Code Online (Sandbox Code Playgroud)

我知道stringbuilder替换函数是错误的.我希望能够接受allowedChars参数中给出的所有字符.这还可以包括斜杠(任何其他类似于我不知道的斜杠的字符?)鉴于此,如何让我的替换功能工作?而且我正在做的方式是正确的吗?我对正则表达式非常新,并且不知道如何使用它们......

Ste*_*edy 7

你需要Regex.Escape在你的字符串上使用.

allowedChars = Regex.Escape(str.ToString());
Run Code Online (Sandbox Code Playgroud)

应该这样做.