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?
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() .
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".
$ means "Match the end of the string" (the position after the last character in the string).
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.
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.
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