简体   繁体   中英

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?

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, eg:

>> "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"

gsub采用了一个块,对于我来说,比无块的方式更容易记住。

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

Not sure about ruby syntax, but:

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

or

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

To be sure you insert space between number and a non number(ie letter or special char):

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

我对ruby不是很熟悉,但是我希望你可以捕获数字,然后像这样插入替换...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM