williamsandonz
williamsandonz

Reputation: 16430

Regular expression does not match when using Regex.Escape

For the code below, I want:

strPattern.IsMatch("@!*()[]{}:?.,^%#$~`:;'_-@!*()[]{}/\\")

to be true, but almost everything I put in the regex is returning false

Essentially I want:

Upvotes: 0

Views: 76

Answers (1)

user2864740
user2864740

Reputation: 61905

Regex.Escape does not handle "-" or "]" and is generally unsuited for the contents of a character class. In this case the resulting regular expression will be wrong1 as they will both have their special meaning.

I would just simplify it and write it manually. I've also removed the redundant characters and fixed other various issues.

 Regex p = new Regex(@"^[]0-9A-Za-z&[@!*(){}:?.,^%#$~`;'_/\\-]*$");
 p.IsMatch("@!*()[]{}:?.,^%#$~`:;'_-@!*()[]{}/\\")  // -> true
 p.IsMatch("Hello`World!")                          // -> true
 p.IsMatch("@<")                                    // -> false

Notes:

  1. To use a ] in a character class, write it as []..] or (verbatim) [..\]..].
  2. To use a - in a character class, write it as [..-] or (verbatim) [..\-..].

Also, "stripping the HTML" is unrelated.


1 The resulting regular expression in the original post is string is

^[0-9A-Za-z&@!\*\(\)\[]\{}:\?\.,\^%\#\$~`:;'_-@!\*\(\)\[]\{}/\\\\]*$

and the error is easy to spot once substituting in a dummy placeholder.

^[characterclass]\{}:\?\.,\^%\#\$~`:;'_-@!\*\(\)\[]\{}/\\\\]*$

Upvotes: 2

Related Questions