【问题标题】:Replacing text with backslashes with perl substitution command使用 perl 替换命令用反斜杠替换文本
【发布时间】:2016-02-11 05:13:19
【问题描述】:

所以我正在编写一个 perl 脚本,该脚本对输入执行替换命令,并且输入将带有反斜杠。所以只需用新文本替换一些文本

例如,如果输入是

"\text"

我可能会输出

"newText"

请注意,斜线已被删除。

这里有一些代码:

$oldText = "\\Text";

while (<STDIN>) {                
    $ln = $_;                     
    $ln2 = $_;
    $ln2 =~ s/\\Text/newText/;  
    $ln =~ s/$oldText/newText/;
}
print "$ln\n";
print "$ln2\n";

当输入是“文本”时,输出是

\newText #Incorrect because the \ is still there

newText #Correct

谁能解释为什么使用字符串而不是变量将输出更改为我想要的?我知道 \ 取消了以下字符的引用,这可能是问题的根源。但我无法理解为什么使用变量会改变输出。将变量 oldText 更改为 "\text" 不会改变输出。

【问题讨论】:

    标签: regex perl backslash


    【解决方案1】:

    使用warnings 会告诉你:

    Unrecognized escape \T passed through in regex; marked by <-- HERE in m/\T <-- HERE ext/ at ...
    

    $oldText = "\\Text" 将字符串 \Text 分配给 $oldText,因此这两个替换不等价。使用\Q(参见quotemeta)引用变量的内容:

    $ln =~ s/\Q$oldText/newText/;
    

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 2011-12-22
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多