I'd like to test if any of the symbols included in the regex pattern
are present in my input
string or not.
1. If Characters That Have Special Meaning in RegEx are Not Escaped
The problem is: if I do not escape the characters that have a special significance in regular expressions, such as the [
and the ]
character, those characters are not included in the test because that nested pair of square brackets is understood by the regex engine to mean another character set to match the input against. So, something like this fails:
static void Main(string[] args)
{
string pattern = "[[]]";
string input = "Foobar";
foreach(var c in pattern)
{
var tempInput = (input + c.ToString());
var isMatch = Regex.IsMatch(tempInput, pattern);
Console.WriteLine($"{c} => {tempInput} => {isMatch}\n\n");
Console.ReadKey();
}
}
Output:
[ => Foobar[ => False
[ => Foobar[ => False
] => Foobar] => False
] => Foobar] => False
2. If RegEx Special Characters Are Escaped
However, if I do escape these characters, then they are unrecognized character sequences and the C# compiler complains as such:
string pattern = "[\[\]]"; // Compiler error: Unrecognized escape sequence
3. C# Literal String With Unescaped Regex Characters
And if I do make the string a literal string by prepending it with the @
symbol, telling C# not to expect an escaped sequence in it like so, then none of the inputs match the regular expression since those unescaped sequences are considered as special characters by the regex engine:
static void Main(string[] args)
{
string pattern = @"[[]]";
...
}
Output:
[ => Foobar[ => False
[ => Foobar[ => False
] => Foobar] => False
] => Foobar] => False
4. C# Literal String With Escaped Regex Characters
And if I make the string a literal string in C# by prepending the string with the @
symbol, and also escape the special regular expression characters, then the regex engine matches even the backward slashes (\
) against the input.
static void Main(string[] args)
{
string pattern = @"[\[\]]"; // @"[!@#$%^&*()_+-=[]{};':""\|,.<>/?]";
...
}
Output:
[ => Foobar[ => True
\ => Foobar\ => False
[ => Foobar[ => True
\ => Foobar\ => False
] => Foobar] => True
] => Foobar] => True
What do I do?