Escaping Special Characters
As we'll see in the later articles in this tutorial, regular expressions can include many special characters that help to define the pattern to match. If you wish to find one of these characters within the input string, you must escape it by prefixing the character with a backslash (\).
To demonstrate, try running the following code. This seems to be searching for the text "dog?". However, as the question mark symbol is a special character in a regular expression, only the three letters of "dog" are actually matched.
string input = "The quick brown fox jumps over the lazy dog?";
Match match = Regex.Match(input, "dog?");
Console.WriteLine("{0}: '{1}' {2} chars", match.Index, match.Value, match.Length);
/* OUTPUT
40: 'dog' 3 chars
*/
To include the question mark, you can escape it, as shown below:
string input = "The quick brown fox jumps over the lazy dog?";
Match match = Regex.Match(input, @"dog\?");
Console.WriteLine("{0}: '{1}' {2} chars", match.Index, match.Value, match.Length);
/* OUTPUT
40: 'dog?' 4 chars
*/
NB: In the above code the regular expression string is preceded by the @ character. This specifies that the text between the quotes is a literal. Without the @, the backslash would require escaping, as it is itself the escape character for C# strings. This means that the second argument would need to be "dog\\?".
2 September 2015