Some characters have one meaning in regular expressions and completely different meanings in other contexts. For example, in regular expressions, the dot (.) is a special character that is used to match any one character. In written language, the period (.) is used to indicate the end of a sentence. In mathematics, the decimal point (.) is used to separate the whole part of a number from the fractional part.
Regular expressions first evaluate a special character in the context of regular expressions: if the expression encounters a dot, it matches any one character.
For example, the regular expression 1.
matches the following:
- 11
- 1A
The regular expression 1.1
matches the following:
- 111
- 1A1
If you were to provide an IP address as a regular expression, you would get unpredictable results. For example, the regular expression 0.0.0.0
matches the following:
- 0102030
- 0a0b0c0
To successfully use regular expressions to identify the dot in its original context as a separator for the different parts of the IP address (and not as a special character that's used to match any other character), you need to provide a signal to that effect. The backslash (\
) is that signal. When a regular expressions encounters a backslash, it recognizes that it should interpret the next character literally. A regular expression to match the IP address 0.0.0.0
would as follows:
0\.0\.0\.0
Use the backslash to escape any special character and interpret it literally; for example:
\\
(escapes the backslash)\[
(escapes the bracket)\{
(escapes the curly brace)\.
(escapes the dot)