문제

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