preg_match_all and preg_replace in Ruby

Spencer picture Spencer · Apr 26, 2011 · Viewed 10.2k times · Source

I am transitioning from php to ruby and I am trying to figure the cognate of the php commands preg_match_all and preg_replace in ruby.

Thank you so much!

Answer

Mike Lewis picture Mike Lewis · Apr 26, 2011

The equivalent in Ruby for preg_match_all is String#scan, like so:

In PHP:

$result = preg_match_all('/some(regex)here/i', 
          $str, $matches);

and in Ruby:

result = str.scan(/some(regex)here/i)

result now contains an array of matches.

And the equivalent in Ruby for preg_replace is String#gsub, like so:

In PHP:

$result = preg_replace("some(regex)here/", "replace_str", $str);

and in Ruby:

result = str.gsub(/some(regex)here/, 'replace_str')

result now contains the new string with the replacement text.