Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable as RegEx pattern

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?

like image 899
Ted Avatar asked Feb 23 '13 14:02

Ted


People also ask

Can I use variable in regex?

If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .

How do I create a pattern in regex?

If you want to match for the actual '+', '. ' etc characters, add a backslash( \ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern. Example : \d+[\+-x\*]\d+ will match patterns like "2+2" and "3*9" in "(2+2) * 3*9".

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


2 Answers

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.

like image 77
ArtMat Avatar answered Sep 27 '22 17:09

ArtMat


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.

like image 35
tchrist Avatar answered Sep 27 '22 17:09

tchrist