Grouping

To apply repetitive matching to any part of a regular expression, all we need to do is enclose that part in parentheses.

/(zub)+/ =~ "zubzub"; $&  #-> "zubzub"

It might not be immediately clear that we are doing something new, but consider that until now we've only applied repetition to individual characters or character groups. Grouping in parentheses does not make a character class. Rather, whatever is inside the parentheses is interpreted as a separate regular expression.

/(zub)+/ =~ "zzuubb"; $&  #-> nil
/[zub]+/ =~ "zzuubb"; $&  #-> "zzuubb"

The regex /zub/ can't find a match anywhere in "zzuubb", but the character class [zub] matches every character in the string. Grouped regular expressions are both far more specific than character ...

Get Sams Teach Yourself Ruby in 21 Days 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.