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.