2013-08-26 32 views
2

這是我的代碼串:的Perl:更換包含問號

$html = 'Is this a question? Maybe.'; 
$old = 'question?'; 
$new = 'reply?'; 

$html =~ s/$old/$new/g; 
print $html; exit; 

輸出是:

Is this a reply?? Maybe. 

期望輸出繼電器:

Is this a reply? Maybe. 

我在做什麼錯?謝謝。

回答

9

使用quotemeta逃離?

$html = 'Is this a question? Maybe.'; 
$old = quotemeta 'question?'; 
$new = 'reply?'; 

$html =~ s/$old/$new/g; 
print $html; exit; 
2

?在正則表達式有特殊的意義。你只需要逃避它在你的模式:

$old = 'question\?'; 
6

在正則表達式中,問號是運營商的意思一個或沒有。因此,我們必須逃避它:

s/question\?/reply?/g 

請注意,它並不是特殊的字符串。因爲將隨機字符串插入正則表達式可能會產生這種不需要的效果,所以您應該首先使用quotemeta

  • 要麼通過使用quotemeta功能:$old = quotemeta "question?"
  • 或通過在正則表達式使用\Q...\E區域:

    s/\Q$old\E/$new/g