假设我有一个字符串"我在24个国家的54个房子里养了36只狗"。是否有可能仅使用gsub在每个数字之间添加",以便字符串变成"我在24个国家的54个房子里有36只狗"?
gsub(/(d)(d)/, "#{$1} #{$2}")
不能工作,因为它将每个数字替换为一个空格,gsub(/dd/, "d d")
也不能工作,它将每个数字替换为d
。
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, '1 ')
#=> "I have 3 6 5 1 dogs in 2 4 countries"
正面的look - behind也可以用:
s.gsub(/(?<=d)(d)/, ' 1')
使用block
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"
另一种方法是使用前向和后向查找数字之间的位置,然后将其替换为空格。
[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"
为了引用匹配项,您应该使用n
,其中n
是匹配项,而不是$1
。
s = "I have 36 dogs in 54 of my houses in 24 countries"
s.gsub(/(d)(d)/, '1 2')
# => "I have 3 6 dogs in 5 4 of my houses in 2 4 countries"