Regex with named capture groups getting all matches in Ruby

前端 未结 10 1974
滥情空心
滥情空心 2021-02-02 08:12

I have a string:

s=\"123--abc,123--abc,123--abc\"

I tried using Ruby 1.9\'s new feature \"named groups\" to fetch all named group info:

10条回答
  •  难免孤独
    2021-02-02 09:12

    I like the match_all given by John, but I think it has an error.

    The line:

      match_datas << md
    

    works if there are no captures () in the regex.

    This code gives the whole line up to and including the pattern matched/captured by the regex. (The [0] part of MatchData) If the regex has capture (), then this result is probably not what the user (me) wants in the eventual output.

    I think in the case where there are captures () in regex, the correct code should be:

      match_datas << md[1]
    

    The eventual output of match_datas will be an array of pattern capture matches starting from match_datas[0]. This is not quite what may be expected if a normal MatchData is wanted which includes a match_datas[0] value which is the whole matched substring followed by match_datas[1], match_datas[[2],.. which are the captures (if any) in the regex pattern.

    Things are complex - which may be why match_all was not included in native MatchData.

提交回复
热议问题