Ruby regex - gsub only captured group

后端 未结 6 777
夕颜
夕颜 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 22:53

    gsub replaces the entire match the regular expression engine produces. Both capturing/non-capturing group constructs are not retained. However, you could use lookaround assertions which do not "consume" any characters on the string.

    "5,214".gsub(/\d\K,(?=\d)/, '.')
    

    Explanation: The \K escape sequence resets the starting point of the reported match and any previously consumed characters are no longer included. That being said, we then look for and match the comma, and the Positive Lookahead asserts that a digit follows.

提交回复
热议问题