I have a Perl program that stores regular expressions in configuration files. They are in the form:
regex = ^/d+$
Elsewhere, the regex gets parsed from the file and stored in a variable - $regex
.
I then use the variable when checking the regex, e.g.
$lValid = ($valuetocheck =~ /$regex/);
I want to be able to include perl variables in the config file, e.g.
regex = ^\d+$stored_regex$
But I can't work out how to do it.
When regular expressions are parsed by Perl they get interpreted twice. First the variables are expanded, and then the the regular expression itself is parsed.
What I need is a three stage process:
First interpolate $regex
, then interpolate the variables it contains and then parse the resulting regular expression.
Both the first two interpolations need to be "regular expression aware". e.g. they should know that the string contain $
as an anchor etc...
Any ideas?
The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit. The \d is standardized to “digit”.
The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, World matches the second word in "Hello World" , so the expression is true.
In addition, Perl defines the following: \w Match a "word" character (alphanumeric plus "_") \W Match a non-word character \s Match a whitespace character \S Match a non-whitespace character \d Match a digit character \D Match a non-digit character.
qr// is one of the quote-like operators that apply to pattern matching and related activities. From perldoc: This operator quotes (and possibly compiles) its STRING as a regular expression. STRING is interpolated the same way as PATTERN in m/PATTERN/.
You can define the regexp in your configuration file like this:
regex = ^\d+(??{$stored_regex})$
But you will need to disable a security check in the block where you're using the regexp by doing this in your Perl program:
use re 'eval';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With