match operators return the character position at which the match occurred. : Match Operator « Development « Ruby






match operators return the character position at which the match occurred.


$& receives the part of the string that was matched by the pattern, 
$` receives the part of the string that preceded the match
$' receivesthe string after the match. 


def show_regexp(a, re) 
    if a =~ re 
        "#{$`}<<#{$&}>>#{$'}" 
    else 
        "no match" 
    end 
end 


puts show_regexp('very interesting', /t/) 
puts show_regexp('this is a test', /a/) 
puts show_regexp('these are all tests', /ll/)
puts show_regexp('zeller', /z/) 

 








Related examples in the same category

1.match operator demo