Regexp rescue method

T

Tim Hunter

th8254 said:
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.
 
J

James Edward Gray II

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:
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
 
F

Florian Aßmann

I can't catch it even with rescue Object... wow.

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

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

Sincerely
Florian
I don't think that raises an error. You'd have to check for a nil
result instead.
=20
I took the question to mean, how would I recover from a malformed Regex= p
error like:
=20
SyntaxError: compile error
(irb):1: invalid regular expression; '[' can't be the last character ie= =2E
can't start range at the end of pattern: /[/
from (irb):1
=20
I don't know of a way to recover from that specific example either,
which is why I didn't jump to answer:
=20
begin ?> re =3D /[/
rescue SyntaxError
puts "Your Regexp is malformed."
end
SyntaxError: compile error
(irb):3: invalid regular expression; '[' can't be the last character ie= =2E
can't start range at the end of pattern: /[/
from (irb):6
=20
But, if you change the way the expression is built, it does seem to
become a recoverable error:
=20
begin ?> re =3D Regexp.new("[")
rescue RegexpError
puts "Your Regexp is malformed."
end
Your Regexp is malformed.
=3D> nil
=20
James Edward Gray II
=20
=20
=20[/QUOTE]
 

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

Forum statistics

Threads
474,262
Messages
2,571,310
Members
47,977
Latest member
MillaDowdy

Latest Threads

Top