Regex Greedy vs Lazy

Control how much quantifiers consume with one character.

  • greedy lazy
  • non-greedy
  • match tag
  • negated class
  • regex performance

Regex Greedy vs Lazy

Control how much quantifiers consume with one character.

Commands

CommandWhat it does
<.+>Greedy: longest possible
<.+?>Lazy: shortest possible
"[^"]*"Negated class for quoted strings
\w+?Lazy word
^.*?:Up to the first colon

Example

'<b>a</b><b>b</b>'.match(/<.+?>/g)

FAQ

Greedy ate my whole line - fix?

Add a question mark for lazy, or better, use a negated class that cannot overshoot by construction.

Is lazy slower?

Sometimes - negated classes are both faster and clearer, so prefer them over lazy dots.

คำถามที่พบบ่อย

Greedy ate my whole line - fix?
Add a question mark for lazy, or better, use a negated class that cannot overshoot by construction.
Is lazy slower?
Sometimes - negated classes are both faster and clearer, so prefer them over lazy dots.

Regex