我有一个简短的问题:是否可以将正则表达式作为字符串存储在变量中(好的,我知道这是可能的)然后执行它?
或者是在变量中存储和使用匹配和替换模式的唯一可能性?
在此先感谢您的帮助!
您可以使用qr//
引号将预编译的正则表达式对象保留在标量变量中:
my $re = qr/foo/;
"foobar" =~ $re; # works
"foobar" =~ /$re/; # the same thing
"foobar" =~ /${re}bar/; # compose your regexes
"foobar" =~ s/$re/baz/; # use in substitutions
"$re"; # a version-dependent stringification of the regex
# that is equivalent to your pattern.