rsturim
rsturim

Reputation: 6846

How do I escape a RegEx?

I have a Regex that I now need to moved into C#. I'm getting errors like this

Unrecognized escape sequence    

I am using Regex.Escape -- but obviously incorrectly.

string pattern = Regex.Escape("^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!@#$%\?\(\)\*\&\^\-\+\=_])).*$");
hiddenRegex.Attributes.Add("value", pattern);

How is this correctly done?

Upvotes: 0

Views: 1142

Answers (2)

Jon
Jon

Reputation: 437366

The error you are getting is due to the fact that your string contains invalid escape sequences (e.g. \d). To fix this, either escape the backslashes manually or write a verbatim string literal instead:

string pattern = @"^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!@#$%\?\(\)\*\&\^\-\+\=_])).*$";

Regex.Escape would be used when you want to embed dynamic content to a regular expression, not when you want to construct a fixed regex. For example, you would use it here:

string name = "this comes from user input";
string pattern = string.Format("^{0}$", Regex.Escape(name));

You do this because name could very well include characters that have special meaning in a regex, such as dots or parentheses. When name is hardcoded (as in your example) you can escape those characters manually.

Upvotes: 0

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

The error you're getting is coming at compile time correct? That means C# compiler is not able to make sense of your string. Prepend @ sign before the string and you should be fine. You don't need Regex.Escape.

See What's the @ in front of a string in C#?

var pattern = new Regex(@"^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!@#$%\?\(\)\*\&\^\-\+\=_])).*$");
pattern.IsMatch("Your input string to test the pattern against");

Upvotes: 4

Related Questions