Regexp captures

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?

On Behalf Of El Gato:

(c = result.match(/id: (\d+)/)) ? c.captures.first :

result.scan(/error: (.*)/).to_s

why not just build the regex and then capture/match.

irb(main):067:0> re = /(id|error): ((\d+)|(.))/
=> /(id|error): ((\d+)|(.
))/
irb(main):068:0> result = “id: 1234”
=> “id: 1234”
irb(main):069:0> c = result.match(re)[2].to_s
=> “1234”
irb(main):070:0> result = “error: this is an error”
=> “error: this is an error”
irb(main):071:0> c = result.match(re)[2].to_s
=> “this is an error”

kind regards -botp

On 30.01.2007 21:25, El Gato wrote:

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. :slight_smile:

Kind regards

robert

Robert K. wrote:

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. :slight_smile:

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs