Get substring after the first = symbol in Ruby

后端 未结 5 1687
盖世英雄少女心
盖世英雄少女心 2021-02-02 05:48

Purely out of curiosity, is there a more elegant way to simply get the substring after the first = symbol in a string? The following works to give back name=b

相关标签:
5条回答
  • 2021-02-02 06:23

    Use String#match

    You can use a regular expression with positive lookbehind to find your match. For example:

    string = "option=name=bob"
    string.match /(?<==).*/
    # => #<MatchData "name=bob">
    

    Use Match Variables to Access Result

    Even if you haven't assigned the match data to a variable, Ruby will store it in special match variables for you.

    $&
    # => "name=bob"
    
    0 讨论(0)
  • 2021-02-02 06:31

    split(char) is another function which can be used. For instance, we want to get substring before char ':' from "answer:computer" then, we can use "answer:computer".split(':')[0].So, we would get result as "answer".

    0 讨论(0)
  • 2021-02-02 06:38

    Not exactly .after, but quite close to:

    string.partition('=').last
    

    http://www.ruby-doc.org/core-1.9.3/String.html#method-i-partition

    0 讨论(0)
  • 2021-02-02 06:40

    There's also this way:

    string.partition('=')[2]
    

    And this one:

    string.sub(/.*?=/, '')
    

    I think I prefer the regexp way you mentioned, though.

    0 讨论(0)
  • 2021-02-02 06:47

    Probably not the Ruby-way (it's a bit cryptic), but you could do this:

    string[/=/]
    $'
    => "name=bob"
    

    or

    /=/ =~ string
    $'
    => "name=bob"
    

    $' is a global holding the string after a successful match. It's nil if nothing is matched, too!

    0 讨论(0)
提交回复
热议问题