0

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?

Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
rsturim
  • 6,756
  • 15
  • 47
  • 59
  • `Regex.Escape` is to escape special characters in a regex pattern so they match verbatim in the input. – Matthew May 02 '12 at 16:41
  • error of ESCAPE is for LANGUAGE COMPILE. \ is need for ESCAPE in STRING. not just REGEX !! MUST escape with \ or use @ – PRASHANT P May 02 '12 at 17:13

2 Answers2

4

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");
Community
  • 1
  • 1
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
0

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.

Jon
  • 428,835
  • 81
  • 738
  • 806