Find both pattern and position of multiple regex matches in Ruby

后端 未结 2 1117
半阙折子戏
半阙折子戏 2021-01-13 08:35

This should be an easy question but I can\'t find anything about it.

Given a regular expression in Ruby, for every match I need to retrieve the matched patterns

相关标签:
2条回答
  • 2021-01-13 09:09

    You can access match data within scan like this:

    "abcdefghij".scan(/\w/) {p $~}
    
    0 讨论(0)
  • 2021-01-13 09:21

    MatchData

    string.scan(regex) do
      $1           # Pattern at first position
      $2           # Pattern at second position
      $~.offset(1) # Starting and ending position of $1
      $~.offset(2) # Starting and ending position of $2
    end
    
    0 讨论(0)
提交回复
热议问题