是否有类似 String#scan 的函数,但返回 MatchDatas 数组?

2024-01-02

我需要一个函数来返回字符串中正则表达式的所有匹配项and找到匹配项的位置(我想突出显示字符串中的匹配项)。

String#match 返回 MatchData,但仅适用于第一个匹配项。

有没有比类似的方法更好的方法

matches = []
begin
  match = str.match(regexp)
  break unless match
  matches << match
  str = str[match.end(0)..-1]
  retry
end

如果您只需要迭代 MatchData 对象,您可以在扫描块中使用 Regexp.last_match,例如:

string.scan(regex) do
  match_data = Regexp.last_match
  do_something_with(match_data)
end

如果你确实需要一个数组,你可以使用:

require 'enumerator' # Only needed for ruby 1.8.6
string.enum_for(:scan, regex).map { Regexp.last_match }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否有类似 String#scan 的函数,但返回 MatchDatas 数组? 的相关文章

随机推荐