Searching for Special Characters

In regular expression syntax, most non-alphanumeric characters are treated as special characters. These characters, called "metacharacters", include asterisks, question marks, dots, slashes, and other non-alphanumeric characters. In order to search for a metacharacter without using its special attribute, precede it with a backslash "\" to change it into a literal character. For example, to build a regex to search for a .txt file, precede the dot with a backslash \.txt to prevent the dot's special function, a wildcard search. The backslash, called an "escape character" in regex terminology, turns metacharacters into literal characters.

Precede the following metacharacters with a backslash "\" to search for them as literal characters:

^ $ + * ? . | ( ) { } [ ] \

Using the backslash "\" to escape special characters in a regular expression.

Example 1: Escape the dollar sign "$" to find the alphanumeric string "$100".

  • Regex:
    \$100
  • Matches:
    $100
    $1000
  • Doesn't Match:
    2100
    100

Example 2: Use the dot "." as a literal character to find a file called "email.txt".

  • Regex:
    email\.txt
  • Matches:
    email.txt
  • Doesn't Match:
    email
    txt
    email_txt

Example 3: Escape the backslash "\" character to search for a Windows file.

  • Regex:
    c:\\readme\.txt
  • Matches:
    c:\readme.txt
  • Doesn't Match:
    c:\\readme.txt
    d:\readme.txt
    c:/readme.txt