Ruby Language Regular Expressions and Regex Based Operations Quantifiers


Quantifiers allows to specify count of repeated strings.

  • Zero or one:

  • Zero or many:

  • One or many:

  • Exact number:

    /a{2,4}/ # Two, three or four
    /a{2,}/  # Two or more
    /a{,4}/  # Less than 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 group site will be set to ''Motor Vehicle Maintenance & Repair' as expected. But if 'Stack Exchange' is an optional part of the string (because it could be 'Stack Overflow' instead), the naive solution will not work as expected:

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

This version will still match, but the named capture will include 'Stack Exchange' since * greedily eats those characters. The solution is to add another question mark to make the * lazy:

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

Appending ? to any quantifier will make it lazy.