C# 正则表达式生成带有未转换字符串的异常
我正试图制作一个简单的程序来根据正则表达式验证字符串,但遇到了一个异常。这是我的密码:C# 正则表达式生成带有未转换字符串的异常,c#,regex,exception,escaping,C#,Regex,Exception,Escaping,我正试图制作一个简单的程序来根据正则表达式验证字符串,但遇到了一个异常。这是我的密码: String exp = "^\\d\\d*$"; Regex r = new Regex(Regex.Unescape(exp)); if (r.IsMatch("")) { Response.Write("strings matches"); } else { Response.Write("strings does not matches"); } 但此代码会生成异常: excepti
String exp = "^\\d\\d*$";
Regex r = new Regex(Regex.Unescape(exp));
if (r.IsMatch(""))
{
Response.Write("strings matches");
}
else
{
Response.Write("strings does not matches");
}
但此代码会生成异常:
exception.Message = "parsing \"^\\d\\d*$\" - Unrecognized escape sequence \\d."
exception.GetType() ={Name = "ArgumentException" FullName = "System.ArgumentException"} System.Type {System.RuntimeType}
有人能告诉我为什么会发生这种情况吗?使用
@
使字符串不会像这样使用转义字符\
String exp=@“^\\d\\d*$”代码>这正是文档所说的。当涉及到无法转换的转义序列时,它抛出一个参数异常,如\d
Regex.Unescape
方法使用适当的字符本身转换字符串转义序列,例如\n
使用0x0A
这里不需要使用Regex.Unescape
方法。
String exp = "^\\d\\d*$";
Regex r = new Regex(exp);
很好
或逐字记录的版本:
String exp = @"^\d\d*$";
Regex r = new Regex(exp);
使用@使字符串不再使用转义字符\如下String exp=@“^\\d\\d*$”代码>