gpt4 book ai didi

regex - Perl,动态生成的带有反斜杠元字符的正则表达式字符串奇怪的行为

转载 作者:行者123 更新时间:2023-12-03 20:50:23 26 4
gpt4 key购买 nike

这是一个小的 perl 片段:

my $n = 1;
my $re_str = '\d';
my $re_str_q = '\Q1\E';

printf "re_str match: %s\n", ($n =~ /$re_str/);
printf "re_str_q match: %s\n", ($n =~ /$re_str_q/);
printf "direct match: %s\n", ($n =~ /\Q1\E/);

运行时产生如下输出:

re_str   match: 1
re_str_q match:
direct match: 1

那么,我的问题是为什么第二个 printf 不匹配?

最佳答案

如果你改变

my $re_str_q = '\Q1\E'; #from 
my $re_str_q = qr/\Q1\E/; #to

这将是传递动态生成的正则表达式的正确方法,然后它会给出以下结果

re_str   match: 1
re_str_q match: 1
direct match: 1

还有如果你用过

use strict;
use warnings;

你会得到一个警告

Unrecognized escape \Q passed through in regex; marked by <-- HERE in m/\Q <-- HERE 1\E/ at so.pl line 9.
Unrecognized escape \E passed through in regex; marked by <-- HERE in m/\Q1\E <-- HERE / at so.pl line 9.

这会给您一些关于出了什么问题的指示。

更新

要更详细地了解这一点,您可以阅读 here

引用文档的摘录

以下转义序列在interpolate 的结构中可用,但在transliterations 中不可用。

\l  lowercase next character only
\u titlecase (not uppercase!) next character only
\L lowercase all characters till \E or end of string
\U uppercase all characters till \E or end of string
\F foldcase all characters till \E or end of string
\Q quote (disable) pattern metacharacters till \E or
end of string
\E end either case modification or quoted section
(whichever was last seen)

参见 quotemeta对于\Q 引用的字符的确切定义。

\L 、\U 、\F 和\Q 可以堆叠,在这种情况下,您每个都需要一个\E 。例如:

say"This \Qquoting \ubusiness \Uhere isn't quite\E done yet,\E is it?";
This quoting\ Business\ HERE\ ISN\'T\ QUITE\ done\ yet\, is it?

关于regex - Perl,动态生成的带有反斜杠元字符的正则表达式字符串奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16795560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com