Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

text

ruby

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

I want to extract jj, aka everything after "your username is: "

One way:

text = "hello john\nyour username is: jj\nthanks for signing up\n"
match = text[/your username is: (.*)/]
value = $1

But this reminds me of perl... and doesn't "read" as naturally as I am told ruby should.

Is there a cleaner way? AKA A "ruby" way?

Thanks

like image 911
SWR Avatar asked May 22 '09 20:05

SWR


1 Answers

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]
like image 84
outis Avatar answered Oct 12 '22 03:10

outis