Say I have a string like this
"some3random5string8"
I want to insert spaces after each integer so it looks like this
"some3 random5 string8"
I specifically want to do this using gsub
but I can't figure out how to access the characters that match my regexp.
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 regexp match. Something like $1
so I could do something like temp.gsub(/\d/, "#{$1 }")
(note, this does not work)
Is this possible?
From the gsub
docs:
If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d, where d is a group number, or \k, where n is a group name. If it is a double-quoted string, both back-references 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 an extra space at the end, use a negative lookahead for the end of line, e.g.:
>> "some3random5string8".gsub(/(\d(?!$))/, '\1 ')
=> "some3 random5 string8"
A positive lookahead checking for a "word character" would also work of course:
>> "some3random5string8".gsub(/(\d(?=\w))/, '\1 ')
=> "some3 random5 string8"
Last but not least, the simplest version without a space at the end:
>> "some3random5string8".gsub(/(\d)(\w)/, '\1 \2')
=> "some3 random5 string8"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With