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?

+3


source to share


4 answers


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"

      

+11


source


gsub

takes a block that is easier for me to remember than a nonchalant way of getting a match.



"some3random5string8".gsub(/\d/){|digit| digit << " "} 

      

+4


source


Not sure about ruby ​​syntax, but:

temp.gsub(/(\d)/, '$1 ')

      

or

temp.gsub(/(\d)/, '\1 ')

      

To insert a space between a number and a number (like a letter or special char):

temp.gsub(/(\d)(\D)/, '$1 $2')

      

+2


source


I'm not very familiar with ruby, but I expect you to be able to write down a digit and then paste into that replacement ...

temp.gsub(/(\d)/, '$1 ')

      

0


source







All Articles