在Ruby中如何匹配子字符串之前,如何删除字符串中的所有字符?
说我有一个字符串: Hey what's up @dude, @how's it going?
我想在@how's
之前删除所有字符。
或者使用正则表达式:
str = "Hey what's up @dude, @how's it going?" str.gsub!(/.*?(?=@how)/im, "") #=> "@how's it going?"
你可以在这里阅读有关环顾的内容
使用String#slice
s = "Hey what's up @dude, @how's it going?" s.slice(s.index("@how")..-1) # => "@how's it going?"
有几种方法可以做到这一点。 以下是我将使用的:
如果要保留原始字符串 :
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?"
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?"]
只获得您感兴趣的部分的简单方法。
>> 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[...]
。
>> "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?"
你也可以直接在字符串上调用[]
(与slice
相同)
s = "Hey what's up @dude, @how's it going?" start_index = s.downcase.index("@how") start_index ? s[start_index..-1] : ""