Regex metacharacters dot star plus question mark explained
dot wildcard, star quantifier, plus quantifier, question mark quantifier, greedy matching, literal escaping
Metacharacters Are Not Literals
Most characters in a regex match themselves. A handful have special meaning — these are metacharacters. The most-used four are . * + ?.
- . — matches any single character except a newline
- * — zero or more of the preceding element
- + — one or more of the preceding element
- ? — zero or one of the preceding element (makes it optional)
Examples
/c.t/.test('cat') // true — dot matches 'a'
/c.t/.test('ct') // false — dot requires exactly one char
/ca*t/.test('ct') // true — zero 'a's is valid
/ca+t/.test('ct') // false — needs at least one 'a'
/colou?r/.test('color') // true
/colou?r/.test('colour') // true
Escaping Metacharacters
To match a literal dot, star, or plus, escape it with a backslash.
/3\.14/.test('3.14') // true — escaped dot matches literal dot
/3\.14/.test('3X14') // false
Greedy by default: * and + consume as many characters as possible while still allowing the overall pattern to match. This matters when patterns overlap — covered in the quantifiers module.
Knowing when to escape is critical. Characters outside a character class that need escaping include: . * + ? ( ) [ ] { } ^ $ | \. Inside a character class [...], most of these lose their special meaning — only ] \ ^ (at start) and - (between chars) need escaping. Memorizing this list is less useful than knowing the rule: if a character has a special function in regex syntax, escape it to use it literally.
