Regex with named capture groups getting all matches in Ruby

前端 未结 10 1975
滥情空心
滥情空心 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:17

    Named captures are suitable only for one matching result.
    Ruby's analogue of findall is String#scan. You can either use scan result as an array, or pass a block to it:

    irb> s = "123--abc,123--abc,123--abc"
    => "123--abc,123--abc,123--abc"
    
    irb> s.scan(/(\d*)--([a-z]*)/)
    => [["123", "abc"], ["123", "abc"], ["123", "abc"]]
    
    irb> s.scan(/(\d*)--([a-z]*)/) do |number, chars|
    irb*     p [number,chars]
    irb> end
    ["123", "abc"]
    ["123", "abc"]
    ["123", "abc"]
    => "123--abc,123--abc,123--abc"
    

提交回复
热议问题