How do I match a repeated character or word with regex quantifiers?
Quick answer
A regex quantifier applies to the item immediately before it: ? means zero or one, * means zero or more, + means one or more, and {n} means exactly n repetitions. To repeat a multi-character word such as ha, group it first: (ha){2}. These meanings and grouping rules are documented for Python’s re module and JavaScript regexes. [S1] [S2]
The question, the details, the next step.
A practical checklist
Write down the complete character or sequence you want to repeat.
Choose
?for zero or one,*for zero or more,+for one or more, or{n}for exactly n repetitions.If the piece has multiple characters, group it before adding the quantifier.
Check which item is immediately before the quantifier; that is what it repeats.
Compare a clear matching example with a near-miss example.
A few more useful answers
What is the difference between `ha{2}` and `(ha){2}`?
Sources
References used for this guide.
- [S1] Python 3.15 Regular Expression Operations: repetition operators docs.python.org · Checked
- [S2] MDN JavaScript Guide: quantifiers and repeated patterns developer.mozilla.org · Checked
