39

I'd like to use a variable as a RegEx pattern for matching filenames:

my $file = "test~";
my $regex1 = '^.+\Q~\E$';
my $regex2 = '^.+\\Q~\\E$';
print int($file =~ m/$regex1/)."\n";
print int($file =~ m/$regex2/)."\n";
print int($file =~ m/^.+\Q~\E$/)."\n";

The result (or on ideone.com):

0
0
1

Can anyone explain to me how I can use a variable as a RegEx pattern?

2 Answers 2

92
+150

As documentation says:

    $re = qr/$pattern/;
    $string =~ /foo${re}bar/; # can be interpolated in other patterns
    $string =~ $re; # or used standalone
    $string =~ /$re/; # or this way

So, use the qr quote-like operator.

Sign up to request clarification or add additional context in comments.

7 Comments

This is exactly what I was looking for! I'm a give you a bounty of 150 points
@GlassGhost - Did you open the bounty before you read this or after? Do you have to wait until it expires to give the points? Anyway, qr// creates a regex object, but you have to be careful what you feed it. If its a literal you must run a quotemeta() on it first.
@sln you have to wait 24 hours in order to spend a bounty.
@sln I'm having trouble getting recursive regexes working on line 22 of: github.com/Viruliant/Tromp/blob/master/Bruijn.pl#L22
@GlassGhost - To be clear, $RecursiveRegex is a variable name and does not represent a recursive regular expression. I looked at your github code. I'm not sure what you are doing so I'll just address the error you're getting. You're using an eval modifier on the substitution form s///e. The substitution side will be executed as code with the result being returned to the caller, the regex engine. For code anything wrapped in paren's is isolated from operators.
|
11

You cannot use \Q in a single-quoted / non-interpolated string. It must be seen by the lexer.

Anyway, tilde isn’t a meta-character.

Add use regex "debug" and you will see what is actually happening.

4 Comments

Thanks, I use $regex =~ s/\\Q(.*?)\\E/quotemeta($1)/ge; to replace \Q..\E. Is there any other way?
@user72757 Yes, don't put \Q \E in your strings in the first place.
strange, it was asked about RegEx as a variable, but it seems the discussion moved to \Q and \E :/
use regex "debug" gave an error. I found that use re "debug" worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.