2012-07-13 53 views
6

我有一個Perl腳本,用於讀取正則表達式搜索並從INI文件中替換值。Perl:通過正則表達式搜索並使用變量替換

這工作正常,直到我嘗試使用捕獲變量($ 1或\ 1)。這些將被$ 1或\ 1逐字地替換。

任何想法如何讓這個捕獲功能工作通過變量傳遞正則表達式位?示例代碼(不使用INI文件)...

$test = "word1 word2 servername summary message"; 

$search = q((\S+)\s+(summary message)); 
$replace = q(GENERIC $4); 

$test =~ s/$search/$replace/; 
print $test; 

這導致...

word1 word2 GENERIC $4 

word1 word2 GENERIC summary message 

感謝

+0

您的搜索模式不會成功,在搜索模式結尾處有**!:**,但不在字符串中。 – tuxuday 2012-07-13 11:32:50

+0

對不起我的錯誤,!:應該已經從示例 – andyml73 2012-07-13 11:36:54

回答

6

使用雙重評價:

$search = q((\S+)\s+(summary message)); 
$replace = '"GENERIC $1"'; 

$test =~ s/$search/$replace/ee; 

注意$replaceee中的雙引號的末尾爲s///

+0

中刪除,這是做的伎倆,歡呼 – andyml73 2012-07-13 11:50:21

-1

使用\ 4,而不是4美元。

$ 4在q()中沒有特殊含義,RE引擎也不會識別它。

\ 4對RE引擎有特殊含義。

+0

Arkadiy,這當然沒有幫助。您需要額外的評估步驟。 – 2012-07-13 12:11:09

+0

哦crep - 我以爲perl做可變插值,然後應用RE語法 - 我想我錯了,變量的值被視爲文字。感謝您指出。 – Arkadiy 2012-07-22 18:53:29

0

嘗試進行正則表達式子到EVAL,予以警告,更換是從外部文件來

eval "$test =~ s/$search/$replace/"; 
0

另一個有趣的解決方案將使用查找aheads (?=PATTERN)

你的例子則只有更換什麼需要更換:

$test = "word1 word2 servername summary message"; 

# repl. only ↓THIS↓ 
$search = qr/\S+\s+(?=summary message)/; 
$replace = q(GENERIC); 

$test =~ s/$search/$replace/; 
print $test; 
+0

我喜歡它,這可能更優雅,謝謝 – andyml73 2012-07-13 12:40:30

0

如果你喜歡阿蒙的解決方案,我認爲「通用$ 1」是不是配置(especia lly'$ 1'部分)。在這種情況下,我認爲有,而無需使用查找aheads的一個更簡單的解決方案:

$test = "word1 word2 servername summary message"; 
$search = qr/\S+\s+(summary message)/; 
$replace = 'GENERIC'; 
$test =~ s/$search/$replace $1/; 

雖然有,當然沒有什麼不好(= PATTERN?)。