Ruby regex - gsub only captured group

后端 未结 6 819
夕颜
夕颜 2021-01-03 22:47

I\'m not quite sure I understand how non-capturing groups work. I am looking for a regex to produce this result: 5.214. I thought the regex below would work, bu

6条回答
  •  醉酒成梦
    2021-01-03 23:02

    It is also possible to use Regexp.last_match (also available via $~) in the block version to get access to the full MatchData:

    "5,214".gsub(/(\d),(\d)/) { |_|
        match = Regexp.last_match
    
        "#{match[1]}.#{match[2]}"
    }
    

    This scales better to more involved use-cases.

    Nota bene, from the Ruby docs:

    the ::last_match is local to the thread and method scope of the method that did the pattern match.

提交回复
热议问题