如果只找到一个捕获组,则 $1 和 $& Perl 之间存在差异

Nat*_*tjo 2 perl regular-expression

据我了解,$&这是最后找到的捕获组。如果只有一个捕获组,为什么不返回相同的两个变量呢?例如:

$ echo "key: value" | perl -ne "s/([a-z]+)(?=:)/\"$1\"/; print;" 
"": value
$ echo "key: value" | perl -ne "s/([a-z]+)(?=:)/\"$&\"/; print;"
"key": value
Run Code Online (Sandbox Code Playgroud)

Sté*_*las 5

perl的特殊变量记录在perldoc perlvar.

如果您的寻呼机是,您可以通过搜索(在行的开头)less到达有关 的部分。$&^\s*\$&$&

或者只是用来perldoc -v '$&'提取有关变量的特定部分$&

$&      The string matched by the last successful pattern match (not
        counting any matches hidden within a BLOCK or "eval()" enclosed
        by the current BLOCK).

        See "Performance issues" above for the serious performance
        implications of using this variable (even once) in your code.

        This variable is read-only and dynamically-scoped.

        Mnemonic: like "&" in some editors.
Run Code Online (Sandbox Code Playgroud)

因此它不包含任何捕获组捕获的内容,而是包含整个正则表达式匹配的内容。

无论如何,这里的问题是shell 将$1其扩展为其第一个位置参数(看起来在您的情况下没有设置),而由于在 shell 中不是有效的变量名称而被单独保留。$&$&

您希望在内部使用单引号,这会$在 shell 中失去其特殊含义:

echo 'key: value' | perl -pe 's/([a-z]+):/"$1":/'
Run Code Online (Sandbox Code Playgroud)
echo 'key: value' | perl -pe 's/[a-z]+(?=:)/"$&"/'
Run Code Online (Sandbox Code Playgroud)

更一般地,您几乎总是希望在代码参数或任何其他语言解释器(, , , ...)周围使用单()引号,不仅因为这些语言通常涉及恰好对 shell 来说也是特殊的字符,还因为,如果不这样做,就会在那里执行 shell 扩展(就像您扩展为此处第一个位置参数的内容一样),这可能很快就会成为代码注入漏洞(想想如果例如包含在这里)。perlsed -eawkpython -csh -c$1$1/;system "reboot" #