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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.