Regexp captures

E

El Gato

I find myself doing something like this a lot lately:

# where result is most often the textual output of a %x{command}
(c = result.match(/id: (\d+)/)) ? c.captures.first : result.scan(/error:
(.*)/).to_s

Is there a smoother/better way to say this?
 
R

Robert Klemme

I find myself doing something like this a lot lately:

# where result is most often the textual output of a %x{command}
(c = result.match(/id: (\d+)/)) ? c.captures.first : result.scan(/error:
(.*)/).to_s

Is there a smoother/better way to say this?

Yes. Use String#[]:

your_match = result[/id: (\d+)/, 1] || result[/error: (.*)/, 1]

Note: your second part "result.scan" will always return at most one
match because of ".*". That's the reason why a single match like mine
yields the same output.

Other alternatives:

This one is more interesting if you extract different portions of the match:

your_match = case result
when /id: (\d+)/
$1
when /error: (.*)/
$1
else
nil
end

In your case you can have it simpler:

your_result = /id: (\d+)/ =~ result || /error: (.*)/ =~ result ? $1 : nil

But I'd prefer the first variant. :)

Kind regards

robert
 
E

El Gato

Robert said:
Yes. Use String#[]:

your_match = result[/id: (\d+)/, 1] || result[/error: (.*)/, 1]

Note: your second part "result.scan" will always return at most one
match because of ".*". That's the reason why a single match like mine
yields the same output.

Other alternatives:

This one is more interesting if you extract different portions of the
match:


But I'd prefer the first variant. :)

Kind regards

robert


Wow! Thanks a bunch Robert. I had never seen String#[] before. That's
a lot cleaner than my version. I appreciate the help and input from
both of you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top