2017-08-08 5 views
0

'you''u'、および'youuuu'(数字は'u')のすべてのインスタンスを'your sister'の文字列に置き換えることです。Replaceは句読点を削除しますか?

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

を書かれています。 –

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

この正規表現は、従来、 "uはyouuuu uyou" という文字列に対して所望の戻り値は何

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

ワウありがとうございました!非常に良い内訳... –

1

私はreplaceを使用する代わりに、youを姉妹と置き換えてgsubを使用して、感嘆符を保持すると思います。 replaceが渡されています文字列全体、例えば代わる

ので:あなたに期待される出力を与えるだろう、あなたの入力にGSUB使用

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

注:

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

だからあなたが試みることができます。

2

ルビに空白を含む文字列を分割すると、それに句読点が付きます。

"I like candy!"のような文を分割してみてください。最後の要素を検査します。あなたは「キャンディー」という言葉に気付くでしょう。感嘆符とすべて。

関連する問題