O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required