【发布时间】:2011-08-13 02:22:50
【问题描述】:
我正在从 php 过渡到 ruby,我正在尝试找出 ruby 中 php 命令 preg_match_all 和 preg_replace 的同源。
非常感谢!
【问题讨论】:
标签: php ruby-on-rails ruby preg-replace preg-match-all
我正在从 php 过渡到 ruby,我正在尝试找出 ruby 中 php 命令 preg_match_all 和 preg_replace 的同源。
非常感谢!
【问题讨论】:
标签: php ruby-on-rails ruby preg-replace preg-match-all
preg_match_all 在 Ruby 中的等价物是 String#scan,如下所示:
在 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,如下所示:
在 PHP 中:
$result = preg_replace("some(regex)here/", "replace_str", $str);
在 Ruby 中:
result = str.gsub(/some(regex)here/, 'replace_str')
result 现在包含带有替换文本的新字符串。
【讨论】:
对于 preg_replace 你可以使用string.gsub(regexp, replacement_string)
"I love stackoverflow, the error".gsub(/error/, 'website')
# => I love stack overflow, the website
字符串也可以是变量,但您可能已经知道了。如果你使用 gsub!原始字符串将被修改。 更多信息http://ruby-doc.org/core/classes/String.html#M001186
对于 preg_match_all 你可以使用string.match(regexp)
这将返回一个 MatchData 对象 (http://ruby-doc.org/core/classes/MatchData.html)。
"I love Pikatch. I love Charizard.".match(/I love (.*)\./)
# => MatchData
或者你可以使用string.scan(regexp),它返回一个数组(我想这就是你要找的)。
"I love Pikatch. I love Charizard.".scan(/I love (.*)\./)
# => Array
匹配:http://ruby-doc.org/core/classes/String.html#M001136
扫描:http://ruby-doc.org/core/classes/String.html#M001181
编辑:迈克的回答看起来比我的要简洁得多......应该会批准他的。
【讨论】:
应该接近 preg_match
"String"[/reg[exp]/]
【讨论】: