3.5. Using Quantifiers

A big part of regular expressions is handling optional items and repetition. An item followed by a question mark is optional; it may be present or absent, and the match depends on the rest of the regex. (It doesn’t make sense to apply this to an anchor but only to a subpattern of non-zero width.)

pattern = /ax?b/
pat2    = /a[xy]?b/
pattern =~ "ab"     # 0
pattern =~ "acb"    # nil
pattern =~ "axb"    # 0
pat2    =~ "ayb"    # 0
pat2    =~ "acb"    # nil

It is common for entities to be repeated an indefinite number of times (which we can specify with the + quantifier). For example, this pattern matches any positive integer:

pattern = /[0-9]+/
pattern =~ "1"         # 0
pattern =~ "2345678"   # 0

Another common occurrence is a pattern that occurs zero or ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.