11

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!

Spencer
  • 21,348
  • 34
  • 85
  • 121

3 Answers3

22

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.

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
3

For preg_replace you would use string.gsub(regexp, replacement_string)

"I love stackoverflow, the error".gsub(/error/, 'website') 
# => I love stack overflow, the website

The string can also be a variable, but you probably know that already. If you use gsub! the original string will be modified. More information at http://ruby-doc.org/core/classes/String.html#M001186

For preg_match_all you would use string.match(regexp) This returns a MatchData object ( http://ruby-doc.org/core/classes/MatchData.html ).

"I love Pikatch. I love Charizard.".match(/I love (.*)\./)
# => MatchData

Or you could use string.scan(regexp), which returns an array (which is what you're looking for, I think).

"I love Pikatch. I love Charizard.".scan(/I love (.*)\./)
# => Array

Match: http://ruby-doc.org/core/classes/String.html#M001136

Scan: http://ruby-doc.org/core/classes/String.html#M001181

EDIT: Mike's answer looks much neater than mine... Should probably approve his.

omninonsense
  • 6,644
  • 9
  • 45
  • 66
0

Should be close for preg_match

"String"[/reg[exp]/]
Kyle Macey
  • 8,074
  • 2
  • 38
  • 78