2015-09-20 86 views
2

假設我有一個字符串「我在24個國家的54個房屋中有36條狗」。 是否有可能通過僅使用gsub在每個數字之間添加一個「」,以便字符串變成「我在2個4個國家的我的房屋的5個4中有3只6只狗」?使用gsub在字符之間插入空格 - Ruby

gsub(/(\d)(\d)/, "#{$1} #{$2}")不起作用,因爲它會用空格替換每個數字,gsub(/\d\d/, "\d \d")也不會起作用,它會用d替換每個數字。

+1

你應該取代 「數」 「數字」。爲什麼急於選擇答案?通過這樣做,您可能會阻止其他答案,並且在綠色閃光燈開啓時仍然準備好答案的人可能不會理解它。沒有急於。我建議你至少等上幾個小時。 –

+0

你只關心有兩位數的子串嗎?這看起來很奇怪。如果子字符串可能有兩個以上的數字,你想要返回什麼?例如,如果字符串是「123狗」,你想要「1 23只狗」,「1 2 3只狗」還是其他什麼東西返回? –

回答

0

爲了參考比賽你應該使用\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" 
+1

我不知道OP是否希望''我有365只狗'.gsub(/(\ d)(\ d)/,'\ 1 \ 2')=>「我有3只狗」或「我有3 6 5只狗''。 –

+0

是的,但這不是他的規範的一部分,因此我沒有對此做出任何決定。 –

+0

@CarySwoveland:假設它確實需要「3 6 5」。你會怎麼做? – Charles

1

另一種方法是使用lookahead和lookbehead查找數字之間的位置,然後用空格替換它。

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

正回顧後也可使用:

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

使用塊

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" 
相關問題