Php Ruby中的preg_match_all和preg_replace

Php Ruby中的preg_match_all和preg_replace,php,ruby-on-rails,ruby,preg-replace,preg-match-all,Php,Ruby On Rails,Ruby,Preg Replace,Preg Match All,我正在从php过渡到ruby,并试图在ruby中找出php命令preg_match_all和preg_replace的同源项 非常感谢你 应接近预匹配 "String"[/reg[exp]/] Ruby中的preg\u match\u all等价物如下: 在PHP中: $result = preg_match_all('/some(regex)here/i', $str, $matches); $result = preg_replace("some(regex)her

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


非常感谢你

应接近预匹配

"String"[/reg[exp]/]

Ruby中的
preg\u match\u all
等价物如下:

在PHP中:

$result = preg_match_all('/some(regex)here/i', 
          $str, $matches);
$result = preg_replace("some(regex)here/", "replace_str", $str);
在Ruby中:

result = str.scan(/some(regex)here/i)
result = str.gsub(/some(regex)here/, 'replace_str')
result
现在包含一个匹配数组

在Ruby中,preg_replace的等价物如下:

在PHP中:

$result = preg_match_all('/some(regex)here/i', 
          $str, $matches);
$result = preg_replace("some(regex)here/", "replace_str", $str);
在Ruby中:

result = str.scan(/some(regex)here/i)
result = str.gsub(/some(regex)here/, 'replace_str')

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

对于preg\u replace,您将使用
string.gsub(regexp,replacement\u string)

字符串也可以是变量,但您可能已经知道了。如果你使用gsub!将修改原始字符串。 更多信息请访问

对于preg\u match\u,您可以使用
string.match(regexp)
这将返回一个MatchData对象()

或者您可以使用
string.scan(regexp)
,它返回一个数组(我想这就是您要查找的)

匹配:

扫描:

编辑:迈克的答案看起来比我的要整洁得多。。。他应该同意他的建议