【问题标题】:Regex generate exceptionwith unescaped string正则表达式生成带有未转义字符串的异常
【发布时间】:2014-03-26 10:06:01
【问题描述】:

我正在尝试制作一个简单的程序来根据正则表达式验证字符串,但我遇到了一个异常。这是我的代码:

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*$";

标签: c# regex exception escaping


【解决方案1】:

这正是Regex.Unescape 的文档所说的。当涉及到无法转换的转义序列时,它会引发 Argument 异常,例如 \d

Regex.Unescape 方法将字符串转义序列与适当的字符本身进行转换,例如\n0x0A

这里不需要使用Regex.Unescape方法。

String exp = "^\\d\\d*$";
Regex r = new Regex(exp);

没问题。

或逐字版本:

String exp = @"^\d\d*$";
Regex r = new Regex(exp);

【讨论】:

    【解决方案2】:

    使用@ 使字符串不使用转义字符\ 像这样

    String exp = @"^\\d\\d*$";

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 1970-01-01
      • 2011-03-11
      • 2010-09-21
      相关资源
      最近更新 更多