Is there a function like String#scan, but returning array of MatchDatas?

前端 未结 4 1381
名媛妹妹
名媛妹妹 2021-02-04 18:18

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).

There

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 18:59

    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 }
    

提交回复
热议问题