2017-08-08 78 views
0

我的任務是用'your sister'替換字符串中'you''u''youuuu'(號碼爲'u')的所有實例。替換刪除標點符號?

這裏是我的代碼:

def autocorrect(input) 
    words = input.split() 
    words.each do |word| 
    if word == 'u' || word == 'you' 
     word.replace 'your sister' 
    elsif word.include? 'you' 
     word.replace 'your sister' 
    end 
    end 
    words = words.join(' ') 
    words 
end 

我的代碼替換正確的詞,但它還會刪除標點符號。我得到這個:

autocorrect("I miss you!") 
# => "I miss your sister" 

輸出中沒有感嘆號。有人知道爲什麼會發生這種情況嗎?

+2

什麼是字符串所需的返回值 「uyou youuuu U」。 –

+0

我意識到我的代碼不適用於所有測試。期望的輸出將是「你的妹妹你的妹妹」,測試是要求替換'你',但不是當它的另一個字的一部分 –

+0

這就是我通過測試的方式: –

回答

1

部分基於對該問題的評論,我假設被替換的子字符串不能在緊接前面或後面跟上一個字母。

r =/
    (?<!\p{alpha}) # do not match a letter (negative lookbehind) 
    (?:   # begin non-capture group 
     you+   # match 'yo' followed by one of more 'u's 
     |   # or 
     u   # match 'u' 
    )    # close non-capture group 
    (?!\p{alpha}) # do not match a letter (negative lookahead) 
    /x    # free-spacing regex definition mode 

"uyou you youuuuuu &you% u ug".gsub(r, "your sister") 
    #=> "uyou your sister your sister &your sister% your sister ug" 

這個正則表達式通常寫

/(?<!\p{alpha})(?:you+|u)(?!\p{alpha})/ 
+0

謝謝先生!很好的細分... –

1

我認爲改爲使用替換,你可以使用gsub,替換you,與你的妹妹,這樣它保持感嘆號。

因爲replace將取代真實傳遞的整個字符串,如:

p 'you!'.replace('your sister')  # => "your sister" 
p 'you!'.gsub(/you/, 'your sister') # => "your sister!" 

所以,你可以嘗試使用:

def autocorrect(input) 
    words = input.split() 
    words.each do |word| 
    if word == 'u' || word == 'you' 
     word.replace 'your sister' 
    elsif word.include? 'you' 
     word.gsub!(/you/, 'your sister') 
    end 
    end 
    words = words.join(' ') 
    words 
end 

p autocorrect("I miss you!") 
# => "I miss your sister!" 

注意只使用GSUB你的投入會得到預期的輸出。

2

當你在ruby中用空白符分割一個字符串時,它會帶上標點符號。

嘗試拆分一個句子,如「我喜歡糖果!」並檢查最後一個元素。你會注意到它是「糖果!」感嘆號和所有。