2014-09-27 54 views
0

我正在从事语言翻译项目,并被卡在中间的某处。修改和替换一个字符串中的引用子字符串

我有情况有像

print "$Hi $There","$Welcome $Aboard" 

一个字符串,我想

print "Hi There", "Welcome Aboard" 

即提取引述子,剥去“$”,并用新的替换原来的子。

我能够提取和更改引用的子字符串,但是当我尝试在原始字符串中替换它们时,它不起作用。向您展示示例代码:

#!/usr/bin/perl 
use strict; 
use warnings; 

my $str = "print \"\$Hi \$There\",\"\$Welcome \$Aboard\""; 
print "Before:\n$str\n"; 
my @quoted = $str =~ m/(\".*?\")/g; #Extract all the quoted strings 
foreach my $subStr (@quoted) 
{ 
    my $newSubStr = $subStr; 
    $newSubStr =~ s/\$//g; #Remove all the '$' 

    $str =~ s/$subStr/$newSubStr/g; #Replace the string**::Doesn't work** 
} 
print "After:\n$str\n"; 

我不知道为什么替换失败。将不胜感激的帮助。

回答

0

您需要在正则表达式中添加\Q\E。您的代码是这样的:

#!/usr/bin/perl 
use strict; 
use warnings; 

my $str = "print \"\$Hi \$There\",\"\$Welcome \$Aboard\""; 
print "Before:\n$str\n"; 
my @quoted = $str =~ m/(\".*?\")/g; #Extract all the quoted strings 
foreach my $subStr (@quoted) 
{ 
    my $newSubStr = $subStr; 
    $newSubStr =~ s/\$//g; #Remove all the '$' 

    $str =~ s/\Q$subStr\E/$newSubStr/g; # Notice the \Q and \E 
} 
print "After:\n$str\n"; 

发生了什么事是你$subStr这个样子的,例如:"$Hi $There"

我不知道,如果它被解释$Hi$There作为变量,但它不像你想要的那样匹配文字字符串。您可以阅读quotemeta docs中的\Q\E

+0

非常感谢。这工作完美。 我不解释'$你好'等等...为了将python代码翻译成perl,这是一个粗糙的中介解析步骤,我把'$'放在每个单词的前面,然后从关键字,字符串等中删除。 感谢您的帮助:) – Udeeksh 2014-09-27 06:13:16

0

试试这段代码:当你想提取出现在双引号中的子字符串,并在双引号中去掉$。你可以试试下面的代码

代码:

#!/usr/bin/perl  
use strict; 
use warnings; 

my $str = "print \"\$Hi \$There\",\"\$Welcome \$Aboard\""; 
print "Before:\n$str\n"; 

while($str =~ m/(\"[^\"]*\")/isg) #Extract all the quoted strings 
{ 
     $str =~ s/\$//isg; # Strip $ from $str 
    } 
print "After:\n$str\n"; 

Perl的一个班轮代码:

perl -0777 -lne "if($_ =~ m/\".*?\"/isg) {$_ =~ s/\$//isg; print $_;} else { print $_;}" Inputfile 
0

你目前的问题是,因为你是不是在你的正则表达式的LHS使用你的文字值quotemeta,像$这样的特殊字符不被转义。

但是,您正在使用错误的工具开始。

如果你很想符合使用m//然后更换使用s///,则很可能需要使用一个使用/e Modifier替换块,这样就可以在RHS执行代码。

以下是您正在尝试的搜索和替换。请注意,我怎么才4个变量3中创建新的价值观,也包括一个可变双引号之外,以显示它是如何不被替换:

#!/usr/bin/perl 
use strict; 
use warnings; 

my %substitute = (
    '$Hi'  => 'Bye', 
    '$There' => 'Somewhere', 
    '$Aboard' => 'Away', 
); 

my $str = 'print "$Hi $There","$Welcome $Aboard", $Hi'; 

$str =~ s{(".*?")}{ 
    (my $quoted = $1) =~ s{(\$\w+)}{ 
     $substitute{$1} || $1 
    }eg; 
    $quoted 
}eg; 

print "$str\n"; 

输出:

print "Bye Somewhere","$Welcome Away", $Hi 

如果你的意图是解析Perl代码,然后你可能应该使用PPI。您可以查看my answers了解使用该模块的一些示例。

相关问题