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!
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!
The equivalent in Ruby for
preg_match_all
isString#scan
, like so:In PHP:
and in Ruby:
result
now contains an array of matches.And the equivalent in Ruby for
preg_replace
isString#gsub
, like so:In PHP:
and in Ruby:
result
now contains the new string with the replacement text.For preg_replace you would use
string.gsub(regexp, replacement_string)
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 ).Or you could use
string.scan(regexp)
, which returns an array (which is what you're looking for, I think).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.
Should be close for preg_match