Ruby中的preg_match_all和preg_replace

Spe*_*cer 11 php ruby ruby-on-rails preg-replace preg-match-all

我正在从php过渡到ruby,我试图在ruby中找出php命令preg_match_all和preg_replace的同源性.

非常感谢!

Mik*_*wis 22

Ruby中的等价物preg_match_allString#scan这样的:

在PHP中:

$result = preg_match_all('/some(regex)here/i', 
          $str, $matches);
Run Code Online (Sandbox Code Playgroud)

在Ruby中:

result = str.scan(/some(regex)here/i)
Run Code Online (Sandbox Code Playgroud)

result 现在包含一系列匹配项.

Ruby中的等价物preg_replaceString#gsub这样的:

在PHP中:

$result = preg_replace("some(regex)here/", "replace_str", $str);
Run Code Online (Sandbox Code Playgroud)

在Ruby中:

result = str.gsub(/some(regex)here/, 'replace_str')
Run Code Online (Sandbox Code Playgroud)

result 现在包含带有替换文本的新字符串.