2013-01-22 43 views
3

我正在使用一個允許使用正則表達式的NginX替換過濾器。我可以用基本的方式得到它,即用telephone替換phone,但我似乎無法讓它有條件地替換一串文本。我可以使用正則表達式創建條件查找和替換嗎?

這裏是XML的檢查檢查:

eat apples cantaloupe bananas often 

我想執行以下規則集:

  1. 查找開始eatoften
  2. 結尾的字符串
  3. 如果字符串包含bananas,則用and especially bananas替換bananas
  4. 如果字符串不包含香蕉沒有做任何字符串

我知道,我可以使用這樣的事情,使部分字符串可供選擇:

/(eat.*)(bananas)?(.*often)/ 

我可以使用以下治做替換假設bananas存在:

$1 and especially $2 $3 

但如果bananas不存在,這會給一個奇怪的結果:

輸入

eat apples cantaloupe often 

輸出:

eat apples cantaloupe and especially often 

我需要前瞻操作?我讀過this article,但我仍然遇到麻煩。

回答

3

嘗試使用前瞻:

/(?=.*eat.*bananas.*often) bananas/ 
3

替代無前瞻:

Raw Match Pattern: 
^eat(.*)(bananas)(.*)often$ 

Raw Replace Pattern: 
eat \1 and especially \2 often 

$sourcestring before replacement: 
do not eat bananas often 
eat apples cantaloupe often 
eat apples cantaloupe bananas often 

$sourcestring after replacement: 
do not eat bananas often 
eat apples cantaloupe often 
eat apples cantaloupe and especially bananas often