说我有一个字符串:Hey what's up @dude, @how's it going?
我想在@how's
之前删除所有字符。
答案 0 :(得分:18)
或使用正则表达式:
str = "Hey what's up @dude, @how's it going?"
str.gsub!(/.*?(?=@how)/im, "") #=> "@how's it going?"
您可以阅读here
的外观答案 1 :(得分:13)
s = "Hey what's up @dude, @how's it going?"
s.slice(s.index("@how")..-1)
# => "@how's it going?"
答案 2 :(得分:6)
有几种方法可以做到这一点。以下是我将使用的:
如果您想保留原始字符串:
str = "Hey what's up @dude, @how's it going?"
str2 = str[/@how's.+/mi]
p str, str2
#=> "Hey what's up @dude, @how's it going?"
#=> "@how's it going?"
如果您想改变原始字符串:
str = "Hey what's up @dude, @how's it going?"
str[/\A.+?(?=@how's)/mi] = ''
p str
#=> "@how's it going?"
...或...
str = "Hey what's up @dude, @how's it going?"
str.sub! /\A.+?(?=@how's)/mi, ''
p str
#=> "@how's it going?"
您需要\A
锚定在字符串的开头,并m
标记以确保您在多行之间进行匹配。
也许最简单的是改变原作:
str = "Hey what's up @dude, @how's it going?"
str.replace str[/@how's.+/mi]
p str
#=> "@how's it going?"
答案 3 :(得分:2)
String#slice
和String#index
工作正常,但如果指针不在大海捞针中,则会出现 ArgumentError:范围错误值。
在这种情况下,使用String#partition
或String#rpartition
可能效果更好:
s.partition "@how's"
# => ["Hey what's up @dude, ", "@how's", " it going?"]
s.partition "not there"
# => ["Hey what's up @dude, @how's it going?", "", ""]
s.rpartition "not there"
# => ["", "", "Hey what's up @dude, @how's it going?"]
答案 4 :(得分:1)
只获取您感兴趣的部分的简便方法。
>> s="Hey what's up @dude, @how's it going?"
=> "Hey what's up @dude, @how's it going?"
>> s[/@how.*$/i]
=> "@how's it going?"
如果您确实需要更改字符串对象,则可以始终执行s=s[...]
。
答案 5 :(得分:0)
>> "Hey what's up @dude, @how's it going?".partition("@how's")[-2..-1].join
=> "@how's it going?"
不区分大小写
>> "Hey what's up @dude, @HoW's it going?".partition(/@how's/i)[-2..-1].join
=> "@HoW's it going?"
或使用scan()
>> "Hey what's up @dude, @HoW's it going?".scan(/@how's.*/i)[0]
=> "@HoW's it going?"
答案 6 :(得分:0)
您也可以直接在字符串上调用[]
(与slice
相同)
s = "Hey what's up @dude, @how's it going?"
start_index = s.downcase.index("@how")
start_index ? s[start_index..-1] : ""