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

后端 未结 7 909
时光说笑
时光说笑 2021-02-13 16:48

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

I\'d like to remove all the characters before@how\'s.

7条回答
  •  执念已碎
    2021-02-13 17:43

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

提交回复
热议问题