Backslash makes special literal, and vice versa
Two facts:
- To match a metacharacter literally, put a backslash in front:
\.matches a dot,\$matches a dollar sign,\\matches a backslash. - To create a special meaning out of an ordinary letter, put a backslash in front:
\dmeans digit,\bmeans word boundary,\nmeans newline.
The backslash is the universal mode flip.
Raw strings save your sanity
In Python, JavaScript template literals, and most languages, the backslash is ALSO the string-escape character. So "\d" in a Python string is interpreted by the string parser before regex sees it — sometimes harmlessly, sometimes catastrophically.
Always use raw strings (or the equivalent) for regex patterns. Python: r"\d+". Rust: r"\d+". JavaScript regex literals: /\d+/ (the slashes provide the same protection).
Without raw strings: "\d" in Python is the same as "\\d" by accident, but "\b" is the ASCII backspace character (8) — your pattern is silently wrong.
Programmatic escaping
If you're building a regex from user input or a variable, use the engine's escape function: Python re.escape(), modern JavaScript RegExp.escape(), or Go regexp.QuoteMeta(). Older JavaScript runtimes need a vetted polyfill. Never concatenate raw user input into a pattern.