Forum: Ruby Regexp rescue method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cc1f82fad5e73398846d66c04c8df213?d=identicon&s=25 th8254 (Guest)
on 2007-06-27 20:41
How would I write a rescue method to recover from a failed regexp
parsing?

-Thanks
3afd3e5e05dc9310c89aa5762cc8dd1d?d=identicon&s=25 Tim Hunter (Guest)
on 2007-06-27 22:06
(Received via mailing list)
th8254 wrote:
> How would I write a rescue method to recover from a failed regexp
> parsing?
>
> -Thanks
>
>
I don't think that raises an error. You'd have to check for a nil result
instead.
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2007-06-27 22:49
(Received via mailing list)
On Jun 27, 2007, at 3:05 PM, Tim Hunter wrote:

> th8254 wrote:
>> How would I write a rescue method to recover from a failed regexp
>> parsing?
>>
>> -Thanks
>>
>>
> I don't think that raises an error. You'd have to check for a nil
> result instead.

I took the question to mean, how would I recover from a malformed
Regexp error like:

 >> re = /[/
SyntaxError: compile error
(irb):1: invalid regular expression; '[' can't be the last character
ie. can't start range at the end of pattern: /[/
         from (irb):1

I don't know of a way to recover from that specific example either,
which is why I didn't jump to answer:

 >> begin
?>   re = /[/
 >> rescue SyntaxError
 >>   puts "Your Regexp is malformed."
 >> end
SyntaxError: compile error
(irb):3: invalid regular expression; '[' can't be the last character
ie. can't start range at the end of pattern: /[/
         from (irb):6

But, if you change the way the expression is built, it does seem to
become a recoverable error:

 >> begin
?>   re = Regexp.new("[")
 >> rescue RegexpError
 >>   puts "Your Regexp is malformed."
 >> end
Your Regexp is malformed.
=> nil

James Edward Gray II
Ee469623eb1b8e6e35d192822b9c4aa2?d=identicon&s=25 Florian Aßmann (Guest)
on 2007-06-27 23:51
(Received via mailing list)
I can't catch it even with rescue Object... wow.

you could also eval it, k, thats even more evil:

begin
  re = eval '/abc/'
  p re
  re = eval '/[/'
rescue SyntaxError
  puts 'hit'
end

Sincerely
Florian

James Edward Gray II schrieb:
This topic is locked and can not be replied to.