是否有像 String#scan 这样的函数,但返回 MatchData 数组?
问题描述:
我需要一个函数来返回字符串中正则表达式的所有匹配和找到匹配的位置(我想突出显示字符串中的匹配).
I need a function to return all matches of a regexp in a string and positions at which the matches are found (I want to highlight matches in the string).
有返回 MatchData 的 String#match,但仅适用于第一场比赛.
There is String#match that returns MatchData, but only for the first match.
有没有比之类的更好的方法来做到这一点
Is there a better way to do this than something like
matches = []
begin
match = str.match(regexp)
break unless match
matches << match
str = str[match.end(0)..-1]
retry
end
答
如果您只需要遍历 MatchData 对象,您可以在 scan-block 中使用 Regexp.last_match,例如:
If you just need to iterate over the MatchData objects you can use Regexp.last_match in the scan-block, like:
string.scan(regex) do
match_data = Regexp.last_match
do_something_with(match_data)
end
如果你真的需要一个数组,你可以使用:
If you really need an array, you can use:
require 'enumerator' # Only needed for ruby 1.8.6
string.enum_for(:scan, regex).map { Regexp.last_match }