match
match(*args)
public
Converts pattern to a Regexp (if it isn’t already one), then invokes its match method on str. If the second parameter is present, it specifies the position in the string to begin the search.
'hello'.match('(.)\1') #=> #<MatchData "ll" 1:"l"> 'hello'.match('(.)\1')[0] #=> "ll" 'hello'.match(/(.)\1/)[0] #=> "ll" 'hello'.match('xx') #=> nil
If a block is given, invoke the block with MatchData if match succeed, so that you can write
str.match(pat) {|m| ...}
instead of
if m = str.match(pat) ... end
The return value is a value from block execution in this case.
String#match will match single token only
>> s = “{{person}} ate {{thing}}”
> “{{person}} ate {{thing}}”
>> r = /{{(.*?)}}/
> {{}}
>> s.match®.captures
> [“person”]
Using String#scan pulls out all tokens you were searching for:
>> s.scan®.flatten
> [“person”, “thing”]
Cheat Sheet
I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE) as used by Ruby’s Regexp class:
http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/