Hone

Lessons · Regex · escaping specials

Literal special characters

Backslash before . * + ? ( ) [ ] { } ^ $ | \ makes it a literal character.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Prices, file extensions, IP addresses, URLs are full of dots and dollars.

How to think about it

Does my text contain a special character? Whenever the text you want contains one of those characters, escape it. A dot that is not escaped matches anything and the bug is silent.

Worked example

pattern: \$\d+\.\d{2}
Literal $, digits, literal dot, two digits.
text: $4.99
Match.
pattern: $\d+.\d{2}
Unescaped: $ is an anchor, . is anything. Matches wrongly or not at all.

Your turn

Match a literal question mark.

?

The trap

In a JavaScript or Python string, backslashes need doubling ('\\d') unless you use a raw string or regex literal.

Practise escaping specials on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.