morpheous1129 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I am building a program which allows users to filter files based on a regular expression that they provide. I want to do some input validation to prevent the script from dying if they messed up on the RE.

My question is this: Is there a way to check the string they entered to verify it's a legitimate RE?

Once I have the RE, I will use File::Find to list files recursively. If a file matches their RE, I'll skip it.

One example of a problem I might run into is if they were to specify this as their RE:

/skipthis/file/

I thought maybe I could do it this way, but it doesn't test true if the string doesn't match their legitimate RE:

$RE = <their regular expression>
$Anytext = "test";
$Anytext =~ s/$RE// || print "This is not a valid RE.\n";

The problem here is that if $Anytext doesn't match the RE, it'll tell me the RE is invalid.

Any ideas?

Thank you,

Morpheous1129 (Sean McDaniel)
  • Comment on Input Validation - verifying a string is a properly formatted regular expression

Replies are listed 'Best First'.
Re: Input Validation - verifying a string is a properly formatted regular expression
by moritz (Cardinal) on Mar 17, 2009 at 15:34 UTC
    The problem here is that if $Anytext doesn't match the RE, it'll tell me the RE is invalid

    If $RE is not a valid regex, then it will throw an error, which you can catch with a BLOCK eval

    .
    my $is_valid = eval { qr{$RE}; 1 }

    should work (not tested).

    You could also use some modules like Regexp::Parser or YAPE::Regex if you don't want to interpolate the regex without knowing first if it's valid.

Re: Input Validation - verifying a string is a properly formatted regular expression
by JavaFan (Canon) on Mar 17, 2009 at 15:36 UTC
    I'd do (untested):
    my $re = input-from-user; eval {my $dummy = qr/$re/; 1} or die "Illegal regexp";
    You might want to use use re "eval" if you want your users to use (?{ }) and (??{ }). Of course, you only do that if you can trust your users.
Re: Input Validation - verifying a string is a properly formatted regular expression
by morpheous1129 (Initiate) on Mar 17, 2009 at 21:18 UTC
    An eval works perfect. Thanks a ton!!

    Morpheous1129 (Sean McDaniel)