In a .NET Regex
pattern, what special characters need to be escaped in order to be used literally?
Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.
(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \. accordingly.
Colon does not have special meaning in a character class and does not need to be escaped.
The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.
I don't know the complete set of characters - but I wouldn't rely on the knowledge anyway, and I wouldn't put it into code. Instead, I would use Regex.Escape
whenever I wanted some literal text that I wasn't sure about:
// Don't actually do this to check containment... it's just a little example. public bool RegexContains(string haystack, string needle) { Regex regex = new Regex("^.*" + Regex.Escape(needle) + ".*$"); return regex.IsMatch(haystack); }
Here is the list of characters that need to be escaped to use them as normal literals:
[
\
^
$
.
|
?
*
+
(
and the closing round bracket )
{
#
These special characters are often called "metacharacters".
But, I agree with Jon to use Regex.Escape
instead of hardcoding these character in code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With