Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top