Reputation: 16430
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:
Everything else should fail
string escapedPattern1 = Regex.Escape("@!*()[]{}");
string escapedPattern2 = Regex.Escape(":?.,^%#$~`:;'_-");
string escapedPattern3 = Regex.Escape("@!*()[]{}");
string escapedPattern4 = Regex.Escape(@"/\\");
string stripped = securityHelper.StripHtml(value);
string totalPattern = "0-9A-Za-z&" + escapedPattern1 + escapedPattern2 + escapedPattern3 + escapedPattern4;
Regex strPattern = new Regex("^[" + totalPattern + "]*$");
Upvotes: 0
Views: 76
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:
]
in a character class, write it as []..]
or (verbatim) [..\]..]
.-
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