Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式生成带有未转换字符串的异常_C#_Regex_Exception_Escaping - Fatal编程技术网

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*$”