str = "hi ram hi shyam hi jhon"
我想要类似的东西:
"ram hi shyam hi jhon"
"ram shyam hi jhon"
答案 0 :(得分:4)
我假设你要删除所有单词的重复出现,而不仅仅是"hi"
。这有两种方法。
1使用String#reverse,Array#reverse和Array#uniq
str = "hi shyam ram hi shyam hi jhon"
str.split.reverse.uniq.reverse.join(' ')
#=> "ram shyam hi jhon"
uniq
状态的文档:“self
按顺序遍历,第一次出现。”
2使用正则表达式
r = /
\b # match a word break
(\w+) # match a word in capture group 1
\s # match a trailing space
(?= # begin a positive lookahead
.* # match any number of characters
\s # match a space
\1 # match the contents of capture group 1
\b # match a word break
) # end the positive lookahead
/x # free-spacing regex definition mode
str.gsub(r, '')
#=> "ram shyam hi jhon"
要删除额外空格,请在正则表达式定义的第三行中将\s
更改为\s+
。
答案 1 :(得分:2)
str = "hi ram hi shyam hi jhon"
删除一个事件:
str.sub('hi', '').strip.squeeze
#⇒ "ram hi shyam hi jhon"
删除n次出现:
n.times { str.replace(str.sub('hi', '').strip.squeeze) }
答案 2 :(得分:1)
您正在寻找sub!
:
str = "hi ram hi shyam hi jhon"
str.sub!("hi ", "")
#=> "ram hi shyam hi jhon"
str.sub!("hi ", "")
#=> "ram shyam hi jhon"
str.sub!("hi ", "")
#=> "ram shyam jhon"
如果您没有修改原始字符串的内容(这不是示例的样子),您可能希望使用sub
代替额外的变量