使用变量作为RegEx模式

Ted*_*Ted 20 regex variables perl

我想使用变量作为RegEx模式来匹配文件名:

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";
Run Code Online (Sandbox Code Playgroud)

结果(或在ideone.com上):

0
0
1
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释如何使用变量作为RegEx模式?

Art*_*rtM 57

正如文件所说:

    $re = qr/$pattern/;
    $string =~ /foo${re}bar/; # can be interpolated in other patterns
    $string =~ $re; # or used standalone
    $string =~ /$re/; # or this way
Run Code Online (Sandbox Code Playgroud)

因此,使用qr类似报价的运算符.


tch*_*ist 7

您不能\Q在单引号/非内插字符串中使用.它必须由词法分析器来看待.

无论如何,代字号不是元字符.

添加use regex "debug",您将看到实际发生的情况.

  • 奇怪的是,它被问及RegEx作为变量,但似乎讨论转移到了`\ Q`和`\ E`:/ (5认同)