2014-09-27 55 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瞭解使用該模塊的一些示例。

相關問題