2017-08-08 91 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中用空白符分割一个字符串时,它会带上标点符号。

尝试拆分一个句子,如“我喜欢糖果!”并检查最后一个元素。你会注意到它是“糖果!”感叹号和所有。