Special Characters and Escaping
Special Characters in Regex
In Regex, certain characters have special meanings and are used to build complex patterns. These characters include .
, ^
, $
, *
, +
, ?
, \
, |
, {}
, []
, ()
. When you need to match these characters literally, you must escape them with a backslash \
.
How to Escape Special Characters
To escape a special character, simply place a backslash before it. For example, to match a literal dot .
or a dollar sign $
, you use \.
and \$
respectively.
const regexDot = /\./;
console.log(regexDot.test('example.com')); // true (matches '.')
const regexDollar = /\$/;
console.log(regexDollar.test('Price: $100')); // true (matches '$')
Example: Matching Special Characters
Let’s see an example that matches a string containing parentheses ()
:
const regexParentheses = /\(.*\)/;
console.log(regexParentheses.test('This is a (test) string.')); // true (matches '(test)')
// Explanation:
// \( : Matches the literal '(' character
// .* : Matches any character (except newline) 0 or more times
// \) : Matches the literal ')' character
Combining Escaped Characters and Metacharacters
You can combine escaped characters with other metacharacters to create more complex patterns. For example, to match a string that starts and ends with parentheses and has any characters in between:
const regexComplex = /^\(.*\)$/;
console.log(regexComplex.test('(This is a test)')); // true (matches the entire string)
console.log(regexComplex.test('This is a (test)')); // false (does not match the entire string)
// Explanation:
// ^ : Start of the string
// \( : Matches the literal '(' character
// .* : Matches any character (except newline) 0 or more times
// \) : Matches the literal ')' character
// $ : End of the string
Exercises
- Write a regular expression that matches a string containing a literal asterisk
*
. - Create a Regex pattern that matches a string containing a literal question mark
?
at the end. - Write a regular expression that matches a string starting with a literal caret
^
and ending with a literal dollar sign$
.
Escaping special characters is essential when you need to include them in your search patterns.