Links in the gsub regexp line
Let's say I have a line like this
"some3random5string8"
I want to insert spaces after each integer so that it looks like this:
"some3 random5 string8"
I specifically want to do this withgsub
, but I can't figure out how to access the characters that match my regex.
For example:
temp = "some3random5string8"
temp.gsub(/\d/, ' ') # instead of replacing with a ' ' I want to replace with
# matching number and space
I was hoping there was a way to reference the regex. Something like $1
, so I could do something like temp.gsub(/\d/, "#{$1 }")
(note this doesn't work)
Is it possible?
source to share
From the gsub
docs:
If the replacement is a string, it will be replaced with the matching text. It can contain backlinks to pattern capture groups of the form \ d, where d is the number of groups, or \ k, where n is the name of the group. If it is a double-quoted string, both backreferences must be preceded by an additional backslash.
This means the following 3 versions will work
>> "some3random5string8".gsub(/(\d)/, '\1 ')
=> "some3 random5 string8 "
>> "some3random5string8".gsub(/(\d)/, "\\1 ")
=> "some3 random5 string8 "
>> "some3random5string8".gsub(/(?<digit>\d)/, '\k<digit> ')
=> "some3 random5 string8 "
Edit: also if you don't want to add extra space at the end, use a negative lookahead for the end of the line, e.g .:
>> "some3random5string8".gsub(/(\d(?!$))/, '\1 ')
=> "some3 random5 string8"
A positive lookahead check on the "word character" will also work, of course:
>> "some3random5string8".gsub(/(\d(?=\w))/, '\1 ')
=> "some3 random5 string8"
Last but not least, the simplest version with no trailing space:
>> "some3random5string8".gsub(/(\d)(\w)/, '\1 \2')
=> "some3 random5 string8"
source to share