method

match

v1_8_6_287 - Show latest stable - Class: String
match(p1)
public

Converts pattern to a Regexp (if it isn’t already one), then invokes its match method on str.

   'hello'.match('(.)\1')      #=> #<MatchData:0x401b3d30>
   'hello'.match('(.)\1')[0]   #=> "ll"
   'hello'.match(/(.)\1/)[0]   #=> "ll"
   'hello'.match('xx')         #=> nil

2Notes

String#match will match single token only

Oleg · Mar 5, 20097 thanks
>> s = "{{person}} ate {{thing}}"
=> "{{person}} ate {{thing}}"
>> r = /\\{\\{(.*?)\\}\\}/
=> {{}}
>> s.match(r).captures
=> ["person"]

Using String#scan pulls out all tokens you were searching for:

>> s.scan(r).flatten
=> ["person", "thing"]

Cheat Sheet

svoop · Feb 10, 2009

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/