Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference matches in a string gsub regexp

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?

like image 687
Dty Avatar asked Dec 01 '22 06:12

Dty


1 Answers

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"
like image 80
Michael Kohl Avatar answered Dec 06 '22 07:12

Michael Kohl