regex - "you can’ t 在 "Programming Perl"中隐藏正则表达式构造中模式的终止分隔符是什么意思?

标签 regex perl

抱歉,我再次需要帮助来理解“Programming Perl”一书中相当复杂的片段。在这里(我不明白的标记为 粗体 ):

patterns are parsed like double-quoted strings, all the normal double-quote conventions will work, including variable interpolation (unless you use single quotes as the delimiter) and special characters indicated with backslash escapes. These are applied before the string is interpreted as a regular expression (This is one of the few places in the Perl language where a string undergoes more than one pass of processing). ...

Another consequence of this two-pass parsing is that the ordinary Perl tokener finds the end of the regular expression first, just as if it were looking for the terminating delimiter of an ordinary string. Only after it has found the end of the string (and done any variable interpolation) is the pattern treated as a regular expression. Among other things, this means you can’t “hide” the terminating delimiter of a pattern inside a regex construct (such as a bracketed character class or a regex comment, which we haven’t covered yet). Perl will see the delimiter wherever it is and terminate the pattern at that point.



一、为什么说Only after it has found the end of the string不是 the end of the regular expression如前所述,它在看哪个?

二、什么意思you can’t “hide” the terminating delimiter of a pattern inside a regex construct ?为什么我不能隐藏终止分隔符 / ,而我可以直接将它放在正则表达式中的任何我想要的位置 /A\/C/或在插值变量中(即使没有 \ ):
my $s = 'A/';
my $p = 'A/C';
say $p =~ /$s/;

输出 1 .

当我在写和重新阅读我的问题时,我认为这个片段讲述了使用单引号作为正则表达式分隔符,然后它看起来非常有凝聚力。我的假设正确吗?

我的赞赏。

最佳答案

它说“字符串的结尾”而不是“正则表达式的结尾”,因为此时它将正则表达式视为只是一个字符串。

它试图说这不起作用:

/foo[-/_]/

即使正常的正则表达式元字符在 [] 中并不特殊, Perl 会将正则表达式视为 /foo[-/并提示未终止的类(class)。

它试图说 Perl 在读取它时不会解析正则表达式。首先它在你的源代码中找到正则表达式的结尾,就好像它是一个带引号的字符串,所以唯一的特殊字符是 \ .然后它插入任何变量。然后它将结果解析为正则表达式。

您可以使用 \ 隐藏终止分隔符因为这适用于普通字符串。您可以将分隔符隐藏在插值变量中,因为在找到分隔符之后进行插值。如果您使用括号分隔符(例如 { }[ ] ),您可以在正则表达式中嵌套匹配的分隔符对,因为 q{}也是这样工作的。
但是您不能将它隐藏在任何其他正则表达式结构中。

关于regex - "you can’ t 在 "Programming Perl"中隐藏正则表达式构造中模式的终止分隔符是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11745013/

相关文章:

python - 如何在 Python 中逐行对文件使用正则表达式

regex - 在 Eclipse 中取消注释 Perl 代码块的正则表达式是什么?

Perl字符编码困惑

linux - 检查文件是否有任何数据损坏

perl - 是否应该在 Perl 中将显式字符编码和编码/解码提升为 "best practice"?

sql - PostgreSQL-拆分行

Java 带条件的重复字符正则表达式

mysql - 使用 Perl 转义 sql 查询错误消息

regex - 如何使用 Powershell 从多行中选择字符串

xml 正则表达式/正则表达式 OR 运算符