开发者

How do I remove all characters in a string until a substring is matched, in Ruby?

Say I have a string: Hey what's up @dude, @how's it going?

I'd like to remove all the c开发者_高级运维haracters before@how's.


or with the regex:

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

you can read about lookaround at here


Use String#slice

s = "Hey what's up @dude, @how's it going?"
s.slice(s.index("@how")..-1)
# => "@how's it going?"


There are literally tens of ways of doing this. Here are the ones I would use:

If you want to preserve the original string:

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?"

If you want to mutate the original string:

str = "Hey what's up @dude, @how's it going?"
str[/\A.+?(?=@how's)/mi] = ''
p str
#=> "@how's it going?"

...or...

str = "Hey what's up @dude, @how's it going?"
str.sub! /\A.+?(?=@how's)/mi, ''
p str
#=> "@how's it going?"

You need the \A to anchor at the start of the string, and the m flag to ensure that you are matching across multiple lines.

Perhaps simplest of all for mutating the original:

str = "Hey what's up @dude, @how's it going?"
str.replace str[/@how's.+/mi]
p str
#=> "@how's it going?"


String#slice and String#index work fine but will blow up with ArgumentError: bad value for range if the needle is not in the haystack.

Using String#partition or String#rpartition might work better in that case:

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?"]


An easy way to get only the part you are interested in.

>> 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?"

If you really need to change the string object, you could always do s=s[...].


>> "Hey what's up @dude, @how's it going?".partition("@how's")[-2..-1].join
=> "@how's it going?"

Case insensitive

>> "Hey what's up @dude, @HoW's it going?".partition(/@how's/i)[-2..-1].join
=> "@HoW's it going?"

Or using scan()

>> "Hey what's up @dude, @HoW's it going?".scan(/@how's.*/i)[0]
=> "@HoW's it going?"


You can also directly call [] also on a string(same as slice)

s = "Hey what's up @dude, @how's it going?"
start_index = s.downcase.index("@how")
start_index ? s[start_index..-1] : ""
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜