Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double interpolation of regular expressions in Perl

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?

like image 943
tomdee Avatar asked Feb 09 '09 11:02

tomdee


People also ask

What is \d in Perl regex?

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”.

What does =~ do in Perl?

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.

What does \s mean in Perl?

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.

What is QR in Perl?

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/.


1 Answers

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';
like image 168
Leon Timmermans Avatar answered Sep 22 '22 07:09

Leon Timmermans