How to test a variable to see if it is a valid regexp pattern?

L

Leif Wessman

How do I test a variable to see if it contains a valid regexp pattern?
Is it possible?

Leif
 
B

Ben Morrow

Quoth (e-mail address removed) (Leif Wessman):
How do I test a variable to see if it contains a valid regexp pattern?
Is it possible?

my $maybe_re = ...;
my $re = eval { qr/$maybe_re/ };
$@ and print "regex wasn't valid: $@";

Ben
 
D

David K. Wall

How do I test a variable to see if it contains a valid regexp pattern?
Is it possible?

my $string = 'tes(ting';
my $regex;
eval { $regex = qr($string); };

print $@ ? 'Invalid regex' : 'Valid regex';
 
K

Kjetil Skotheim

How do I test a variable to see if it contains a valid regexp pattern?
Is it possible?

Leif



Using eval (like those earlier replies suggest) is probably the easyest
way to go.
But be awary of the security implications!

If the regexp's comes from web input, then they could be able to
take control over your webserver. You might concider using
"joker-chars" instead of a full-blown perl-regexp. Then
you could translate the input into a perl-regexp:

my $regexp=$input;
my $legalchars='a-zA-Z0-9...*?';

$regexp=~ s/[^$legalchars]+//gs;
$regexp =~ s/\*/.*/g;
$regexp =~ s/\?/./g;

$regexp = eval{qr/$regexp/};
print "ERROR: $@\n" if $@;


if($information =~ $regexp){
#match!!!
print ...
}
 
B

Ben Morrow

Quoth "Kjetil Skotheim said:
Using eval (like those earlier replies suggest) is probably the easyest
way to go.
But be awary of the security implications!

You are missing the crucial difference between eval "" and eval {}. They
are completely different operations, and shouldn't really have the same
keyword. eval "" is a runtime-evaluation operator, with all the security
risks that implies; eval {} is simply how Perl spells 'catch' (as in
exceptions), and poses no risk whatever.

Ben
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top