tags:

views:

213

answers:

2

Firstly, I was wondering if there was some kind of built in function that would check to see if a regex pattern was valid or not. I don't want to check to see if the expression works - I simply want to check it to make sure that the syntax of the pattern is valid - if that's possible.

If there is no built in function to do so, how do I do it on my own? Do I even need to?

Is there a directory of built in functions/modules that I can search so I can avoid more questions like this? Thank you.

EDIT: I should mention that I plan on generating these patterns on the fly based on user input - which is why I'd like to validate them to make sure they will actually run.

+2  A: 

I'm not quite sure what you mean by "valid" here. If the expression is syntactically out of whack (say, missing a bracket), then the interpreter will let you know and your program won't compile.

But that doesn't protect you from logical or semantic errors. That is, your regular expression may be valid Perl but nuts. Maybe you want something like YAPE::Regex::Explain which will produce an explanation of your regular expression.

Telemachus
+10  A: 

I am no Perl expert, but maybe this can help:

#!/usr/bin/perl

my $pattern = "["; # <-insert your pattern here
my $regex = eval { qr/$pattern/ };
die "invalid regex: $@" if $@;

which returns this:

invalid regex: Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE / at test.pl line 4.

For your second question you could always check out the huge body of work at CPAN.

Adam Bernier
If this is for a server, consider very carefully how you will avoid letting the user generated input execute arbitrary code. I don't know, offhand, how it could happen but that's no assurance.
George Phillips
@George: This is a very good point, thank you for mentioning.
Adam Bernier
I was at borders today, and the perl cookbook suggested eval as well.
misterMatt