Get substring after the first = symbol in Ruby

后端 未结 5 1700
盖世英雄少女心
盖世英雄少女心 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 /(?<==).*/
    # => #
    

    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"
    

提交回复
热议问题