开发者

preg_match_all and preg_replace in Ruby

I am transitioning from php to ruby and I am trying to figure the cognate of the php commands pr开发者_Python百科eg_match_all and preg_replace in ruby.

Thank you so much!


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.


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.


Should be close for preg_match

"String"[/reg[exp]/]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜