Quantifiers

suggest change

Quantifiers say how many times part of a pattern may repeat.

/a?/
/a*/
/a+/
/a{2,4}/ # Two, three, or four
/a{2,}/  # Two or more
/a{,4}/  # At most four, including zero

By default, quantifiers are greedy, which means they take as many characters as they can while still making a match. Normally this is not noticeable:

/(?<site>.*) Stack Exchange/ =~ 'Motor Vehicle Maintenance & Repair Stack Exchange'

The named capture site is set to Motor Vehicle Maintenance & Repair, as expected. Named captures are assigned only when Regexp#=~ is the method that runs (the regexp is on the left). If Stack Exchange is optional, because the site might say Stack Overflow instead, a naive pattern does not do what it looks like:

/(?<site>.*)( Stack Exchange)?/

This still matches, and the named capture includes Stack Exchange, because * eats those characters. A lazy *? is not enough on its own: the optional group may match nothing, and *? then matches nothing. Anchor the end of the string:

/(?<site>.*?)( Stack Exchange)?\z/

Appending ? to any quantifier will make it lazy.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents