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

后端 未结 7 905
时光说笑
时光说笑 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:44

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

提交回复
热议问题