【问题标题】:perl regex using variables [duplicate]使用变量的perl正则表达式[重复]
【发布时间】:2014-01-06 22:36:44
【问题描述】:

这是一个代码sn-p:

$regex_match = "(.*).txt";
$replacement = "\$1.pdf";
my $new_replacement = ""; #???
my $new_regex_match = quotemeta ($regex_match); #???
$from = "test.txt";
(my $to = $from) =~ s{$regex_match}{$replacement}g;
print "From " . $from . " To " . $to  . "\n";

输出: 从 test.txt 到 $1.pdf

我相信 $1 没有被插值。需要改变什么? new_replacement 和/或 new_regex_match 是什么?

【问题讨论】:

  • 你为什么要逃避$?
  • 您可以通过替换扩展名来简化代码:$from=~s/\.txt$/\.pdf/;

标签: regex perl


【解决方案1】:

您需要s///ee 来强制评估。

my $regex_match = '(.*)\.txt';
my $replacement = '$1.".pdf"';

while (<>) {
    s/$regex_match/$replacement/ee;
    print;
}

【讨论】:

  • $replacement = '$1.".pdf"'; 1美元是什么意思。用ee选项做什么?我问是因为我也测试了这个 $replacement = '$1".pdf"';并收到错误。您的解决方案确实有效!谢谢。只是不明白为什么。
  • @Paul ysth 有一个excellent explanation 在我将其链接为欺骗的问题中。
  • 抱歉,在我回答之前没有看到 dup 评论。这是一个很好的解释。 @Paul 简短的回答是你正在评估 Perl 代码,所以你想要这个:$1 . ".pid"。你的扩展为$1 ".pdf",缺少连接运算符。
  • 所以它是第二个 eval 的字符串连接?哇...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多