Ruby regex - gsub only captured group
non capturing groups still consumes the match
use"5,214".gsub(/(\d+)(,)(\d+)/, '\1.\3')
or"5,214".gsub(/(?<=\d+)(,)(?=\d+)/, '.')
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.
You can't. gsub
replaces the entire match; it does not do anything with the captured groups. It will not make any difference whether the groups are captured or not.
In order to achieve the result, you need to use lookbehind and lookahead.
"5,214".gsub(/(?<=\d),(?=\d)/, '.')