使用 gsub - Ruby 在字符之间插入 space

Inserting a space in between characters using gsub - Ruby

假设我有一个字符串 "I have 36 dogs in 54 of my houses in 24 countries"。 是否可以仅使用 gsub 在每个数字之间添加一个“”,以便字符串变为 "I have 3 6 dogs in 5 4 of my houses in 2 4 countries"?

gsub(/(\d)(\d)/, "#{} #{}") 不起作用,因为它用 space 替换每个数字,gsub(/\d\d/, "\d \d") 也没有用 d 替换每个数字。

为了引用匹配项,您应该使用 \n,其中 n 是匹配项,而不是 </code>。</p> <pre><code>s = "I have 36 dogs in 54 of my houses in 24 countries" s.gsub(/(\d)(\d)/, ' ') # => "I have 3 6 dogs in 5 4 of my houses in 2 4 countries"

另一种方法是使用先行和后行查找数字之间的位置,然后将其替换为 space。

[1] pry(main)> s = "I have 36 dogs in 54 of my houses in 24 countries"
=> "I have 36 dogs in 54 of my houses in 24 countries"
[2] pry(main)> s.gsub(/(?<=\d)(?=\d)/, ' ')
=> "I have 3 6 dogs in 5 4 of my houses in 2 4 countries"
s = "I have 3651 dogs in 24 countries"

四种使用方式String#gsub:

使用积极的前瞻和捕获组

r = /
    (\d)   # match a digit in capture group 1
    (?=\d) # match a digit in a positive lookahead
    /x     # extended mode

s.gsub(r, ' ')
  #=> "I have 3 6 5 1 dogs in 2 4 countries"

也可以使用积极的回顾:

s.gsub(/(?<=\d)(\d)/, ' ')

使用块

s.gsub(/\d+/) { |s| s.chars.join(' ') }
  #=> "I have 3 6 5 1 dogs in 2 4 countries"

使用正前瞻和块

s.gsub(/\d(?=\d)/) { |s| s + ' ' }
  #=> "I have 3 6 5 1 dogs in 2 4 countries"

使用哈希

h = '0'.upto('9').each_with_object({}) { |s,h| h[s] = s + ' ' }
  #=> {"0"=>"0 ", "1"=>"1 ", "2"=>"2 ", "3"=>"3 ", "4"=>"4 ",
  #    "5"=>"5 ", "6"=>"6 ", "7"=>"7 ", "8"=>"8 ", "9"=>"9 "} 
s.gsub(/\d(?=\d)/, h)
  #=> "I have 3 6 5 1 dogs in 2 4 countries"