I'm trying to make a simple program to validate a string against a regular expression, but I'm getting an exception. Here is my code:

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

but this code generates the exception:

exception.Message = "parsing \"^\\d\\d*$\" - Unrecognized escape sequence \\d."

exception.GetType() ={Name = "ArgumentException" FullName = "System.ArgumentException"} System.Type {System.RuntimeType}

Can someone tell me why this is happening?

有帮助吗?

解决方案

That is exactly, what the documentation to Regex.Unescape is saying. It throws an Argument exception, when it comes to an escape sequence that it cannot convert, like \d.

The Regex.Unescape methods converts string escape sequences with the appropriate characters itself, e.g. \n with 0x0A.

You don't need to use the Regex.Unescape method here.

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

is just fine.

Or the verbatim version:

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

其他提示

Use @ to make the strings not use the escape character \ like this

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top