preg_match_all and preg_replace in Ruby

2020-08-14 00:14发布

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!

3条回答
我命由我不由天
2楼-- · 2020-08-14 00:40

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-08-14 00:48

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.

查看更多
迷人小祖宗
4楼-- · 2020-08-14 00:56

Should be close for preg_match

"String"[/reg[exp]/]
查看更多
登录 后发表回答