簡體   English   中英

Perl:傳遞正則表達式搜索並使用變量替換

[英]Perl: passing regex search and replace using variables

我有一個Perl腳本,它讀取正則表達式搜索並替換INI文件中的值。

這工作正常,直到我嘗試使用捕獲變量($ 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

謝謝

使用雙重評估:

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

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

注意$replace s///雙引號和@ s///末尾的ee

嘗試將regex-sub置於eval,請注意替換來自外部文件

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

另一個有趣的解決方案是使用前瞻(?=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;

如果你喜歡amon的解決方案,我認為“GENERIC $ 1”不是配置(尤其是'$ 1'部分)。 在這種情況下,我認為有一個更簡單的解決方案,而不使用預測:

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

當然,(?= PATTERN)並沒有什么不好的。

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM