Module lessons (3/4)
The wildcard: the dot `.`
The dot . is the wildcard par excellence of regexes: it matches any single character except for line terminators (\n). It is indispensable for flexible masks of known format, but requires attention because without limits it tends to consume more text than necessary.
Mental model: behavior of the point and flag s
| Patterns | Flags | Test inputs | Result on \n / content | Technical reason |
|---|---|---|---|---|
c.t | g | cat c@t c\nt | Matcha cat and c@t, skip c\nt | By default . excludes \n |
c.t | gs | cat c@t c\nt | Matcha all three (c\nt included) | The s (dotAll) flag enables . over \n |
<p>.*</p> | gs | <p>A</p><p>B</p> | Only one match of the entire row | * is greedy (greedy) |
<p>.*?</p> | gs | <p>A</p><p>B</p> | Two separate matches | .*? is lazy and stops at the first </p> |
Progressive examples
1. Fixed-length single wildcard with .
Pattern: c.t (flag g)
Sample: cat cot c-t c@t c\nt
^^^ ^^^ ^^^ ^^^2. Traversing a multiline block with flag s (dotAll)
const htmlBlock = '<p>prima riga\nseconda riga</p>';
console.log(/<p>.*<\/p>/.test(htmlBlock)); // false (bloccato su \n)
console.log(/<p>.*<\/p>/s.test(htmlBlock)); // true (dotAll attivo)3. Separate multiple blocks without merging them (.*? vs .*)
Sample: [A] testo [B]
Pattern: \[.*\] -> "[A] testo [B]" (un unico match troppo largo)
Pattern: \[.*?\] -> "[A]" e "[B]" (due match distinti)4. Turn s (dotAll) and g on and off live
Guided laboratory
3 wildcard match in brackets
Finds any exact triplet of any 3 characters enclosed in parentheses, such as (abc) or (123).
Show hint
Activate the g flag by keeping the three dots between escape brackets \(...\).
Solution available after 3 attempts
Multiline blocks delimited with s+lazy flag
Extract every block between [INIZIO] and [FINE] even when it contains newlines (\n), stopping at the first closure (.*?) with flag gs.
Show hint
Use \[INIZIO\].*?\[FINE\] and enable both the g and s flags.
Solution available after 3 attempts
Wild card pattern respecting the newline border
Find all sequences of exactly 3 characters starting with c and ending with t (e.g. cat, cot, c-t, c.t).
Show hint
Replace the central letter with the wildcard . keeping only the flag g.
Solution available after 3 attempts
Check for understanding
What is the result of 'a\nb'.match(/a.b/)?
Which string is accidentally matched by the unescaped pattern /10.5/ (default flags)?