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