preg_match_all and preg_replace in Ruby

故事扮演 提交于 2019-12-06 19:44:29

问题


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!


回答1:


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.




回答2:


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.




回答3:


Should be close for preg_match

"String"[/reg[exp]/]


来源:https://stackoverflow.com/questions/5791718/preg-match-all-and-preg-replace-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!