Skip to main content
 首页 » 编程设计

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

2024年01月21日35artech

我正在尝试根据输入的字符来验证字符串。我希望能够设置除字符和数字外还允许哪些字符。下面是我的扩展方法:

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


我使用的方式是:

s string = " te\m@as 1963' yili.ışçöÖÇÜ/nda olbnrdu" // just a test string with no meaning 
if (s.isAlphaNumeric("ışŞö\Ö@üÜçÇ ğ'Ğ/.")) {...} 


当然会给出一个错误:

parsing "^[a-zA-Z0-9ışŞö\Ö@üÜçÇ\sğ'Ğ/.]*$" - Unrecognized escape sequence 


我知道stringbuilder replace函数是错误的。我希望能够接受allowedChars参数中给定的所有字符。这还可以包括斜杠(其他我不知道的类似于斜杠的字符吗?)鉴于此,我如何才能使我的替换功能正常工作?而且我的做法是否正确?我对正则表达式非常陌生,不知道如何使用正则表达式...

请您参考如下方法:

您需要在字符串上使用Regex.Escape。

allowedChars = Regex.Escape(str.ToString()); 


应该这样做。