Ruby 中的 preg_match_all 和 preg_replace [英] preg_match_all and preg_replace in Ruby
本文介绍了Ruby 中的 preg_match_all 和 preg_replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从 php 过渡到 ruby,我试图找出 ruby 中 php 命令 preg_match_all 和 preg_replace 的同源词.
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.
非常感谢!
推荐答案
Ruby 中 preg_match_all
的等效项是 String#scan
,像这样:
The equivalent in Ruby for preg_match_all
is String#scan
, like so:
在 PHP 中:
$result = preg_match_all('/some(regex)here/i',
$str, $matches);
在 Ruby 中:
result = str.scan(/some(regex)here/i)
result
现在包含匹配数组.
在 Ruby 中 preg_replace
的等价物是 String#gsub
,像这样:
And the equivalent in Ruby for preg_replace
is String#gsub
, like so:
在 PHP 中:
$result = preg_replace("some(regex)here/", "replace_str", $str);
在 Ruby 中:
result = str.gsub(/some(regex)here/, 'replace_str')
result
现在包含带有替换文本的新字符串.
result
now contains the new string with the replacement text.
这篇关于Ruby 中的 preg_match_all 和 preg_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文