Module lessons (4/4)
Escaping meta-characters
Characters with syntactic function in the regex language are called meta-characters. They are 12 fundamental special meta-characters (\, ^, $, ., |, ?, *, +, (, ), [, {), plus their respective closing delimiters ], }, and the forward slash / in JavaScript literal notation. To search for them as real text you must precede them with a backslash \.
Mental model: literal vs constructor new RegExp
| Symbol | Special meaning | Like looking for it literally | Real example |
|---|---|---|---|
. | Any character (wildcard) | \. | Extensions .tar.gz, domains v1.0 |
$ | End of string / end of line | \$ | Prices in dollars $19.99 |
? | Quantifier 0 or 1 | \? | Query string ?page=2, questions "Ok?" |
( ) | Capture group | \( \) | Function calls sum(1, 2) |
[ ] | Character class | \[ \] | Log tag [ERROR] |
\ | Escape character | \\ | Path Windows C:\Users |
Progressive examples
1. Escape $ and . in prices
Pattern: \$\d+\.\d\d
Sample: Prezzi: $9.99, $12.50, totale $22.49.
^^^^^ ^^^^^^ ^^^^^^2. Difference between literal /.../ and new RegExp(...) in JavaScript
const priceRe1 = /\$\d+\.\d{2}/g; // 1 backslash nel letterale JS
const priceRe2 = new RegExp('\\$\\d+\\.\\d{2}', 'g'); // 2 backslash nella stringa JS
console.log(priceRe1.source === priceRe2.source); // true3. Escape squares [ ] and brackets ( )
Pattern: \[INFO\]\s+id=\(\d+\)
Sample: [INFO] id=(404)
^^^^^^^^^^^^^^^4. Observe \. and classes together in the step-by-step scanner
Guided laboratory
Exact prices in $N.NN format
Find each price in the format $N.NN (symbol $ literal, one or more digits, true decimal point ., two digits).
Show hint
Add the backslash before the period: \$\d+\.\d\d.
Solution available after 3 attempts
Look for the literal question mark
Find every literal question mark ? within the sentences of the text.
Show hint
Without \, the question mark is an invalid quantifier at the beginning of the pattern: write \?.
Solution available after 3 attempts
Compressed .tar.gz extensions with no false positives
Find all exact extensions .tar.gz ensuring that both points are matched as literal points.
Show hint
Precede both points with \: \.tar\.gz.
Solution available after 3 attempts
Check for understanding
Why does new RegExp('d+') (with only one backslash inside JS string) NOT match numbers as expected?
What is the effect of writing /\?/ as a regex pattern versus simply writing /?/?