在Ruby中,如何匹配字符串中的所有字符,直到匹配子字符串?

时间:2011-03-31 14:13:49

标签: ruby regex string

说我有一个字符串:Hey what's up @dude, @how's it going?

我想在@how's之前删除所有字符。

7 个答案:

答案 0 :(得分:18)

或使用正则表达式:

str = "Hey what's up @dude, @how's it going?"
str.gsub!(/.*?(?=@how)/im, "") #=> "@how's it going?"

您可以阅读here

的外观

答案 1 :(得分:13)

使用String#slice

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#sliceString#index工作正常,但如果指针不在大海捞针中,则会出现 ArgumentError:范围错误值

在这种情况下,使用String#partitionString#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] : ""