use parentheses to group terms within a regular expression : Regexps Group « Development « Ruby






use parentheses to group terms within a regular expression

# Everything within the group is treated as a single regular expression. 

def show_regexp(a, re) 
    if a =~ re 
        "#{$`}<<#{$&}>>#{$'}" 
    else 
        "no match" 
    end 
end 
show_regexp('banana', /an*/) # b<<an>>ana 
show_regexp('banana', /(an)*/) # <<>>banana 
show_regexp('banana', /(an)+/) # b<<anan>>a 

 








Related examples in the same category

1.An unescaped vertical bar(|) matches either the regular expression that precedes it or the regular expression that follows it.
2.\1 refers to the match of the first group
3.unescape HTML
4.Backslash Sequences in the Substitution