What's the “ruby way” to parse a string for a single key/value?

前端 未结 4 1157
我在风中等你
我在风中等你 2020-12-31 10:49

I am trying to parse a multi line string and get the rest of the line following a pattern.

text:

hello john
your username is: jj
thanks for signing up

相关标签:
4条回答
  • 2020-12-31 10:59

    Not sure if it's any more Ruby'ish, but another option:

    >> text = "hello john\nyour username is: jj\nthanks for signing up\n"
    >> text.match(/your username is: (.*)/)[1]
    => "jj"
    
    0 讨论(0)
  • 2020-12-31 11:01

    There's also Regexp#match, which returns a MatchData object, which has all the information you could possibly want.

    irb> match = /your username is: (.*)/.match "hello john\nyour username is: jj\nthanks for signing up\n"
    #=> #<MatchData:0x557f94>
    irb> match.pre_match
    #=> "hello john\n"
    irb> match.post_match
    #=> "\nthanks for signing up\n"
    irb> match[0]
    #=> "your username is: jj"
    irb> match[1]
    #=> "jj"
    
    0 讨论(0)
  • 2020-12-31 11:12

    Your code is pretty much the Ruby way. If you don't want to use the global $1, you can use the 2 arg version String#[]:

    match = text[/your username is: (.*)/, 1]
    
    0 讨论(0)
  • 2020-12-31 11:16

    The split command is mindbogglingly useful. It divides a string into an array of substrings, separating on whatever you pass in. If you don't give it any arguments, it splits on whitespace. So if you know the word you're looking for is the fifth "word" (splitting on both spaces and the return character), you can do this:

    text = "hello john\nyour username is: jj\nthanks for signing up\n"
    match=text.split[5]

    ..but perhaps that's not sufficiently self-documenting, or you want to allow for multi-word matches. You could do this instead:

    midline=text.split("\n")[1]
    match=midline.split("username is: ").last

    Or perhaps this more terse way:

    match=text[/username is: (.*)/,1]

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