user107498
user107498

Reputation:

How can I check if a regex pattern is valid in Perl?

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.

Upvotes: 7

Views: 8091

Answers (4)

Serious Angel
Serious Angel

Reputation: 1555

For example, in a Bash script:

#!/bin/bash

pattern='12[3';
printf '%s' "$pattern" | perl -ne 'eval { qr/$_/ }; die if $@;';
echo $?;

# Outputs (if the pattern is invalid):
#
# Unmatched [ in regex; marked by <-- HERE in m/12[ <-- HERE 3/ at -e line 1, # <> line 1.
#         ...propagated at -e line 1, <> line 1.
# 255

# If valid:
#
# 0

or

#!/bin/bash

pattern='12[3';

if
    printf '%s' "$pattern" \
    | perl -ne 'eval { qr/$_/ }; die if $@;' &> '/dev/null';
then
    printf 'Valid\n';
else
    printf 'Invalid\n';
fi

Also, it should be possible to use environment variables:

#!/bin/bash

export pattern='12[3';

if perl -ne 'eval { qr/$ENV{pattern}/ }; die if $@;' &> '/dev/null';
then #...

Related: Reference 1, Reference 2

Upvotes: 0

Telemachus
Telemachus

Reputation: 19705

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 do terrible things—or do nothing at all. Maybe you want something like YAPE::Regex::Explain which will produce an explanation of your regular expression.

Upvotes: 1

user2291758
user2291758

Reputation: 763

Another cpan module that you can use: Regexp::Parser. From the documentation:

my $parser = Regexp::Parser->new;
if (! $parser->regex($rx)) {
  my $errmsg = $parser->errmsg;
  my $errnum = $parser->errnum;
  # ...
}

Upvotes: 1

mechanical_meat
mechanical_meat

Reputation: 169304

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.

Upvotes: 24

Related Questions