我可以创建一个条件查找&用正则表达式替换?

时间:2013-01-22 00:21:32

标签: regex nginx

我正在尝试使用NginX替换过滤器,它允许使用正则表达式。我可以以基本的方式使用它,即用phone替换telephone,但我似乎无法有条件地替换一串文本。

这是检查XML的检查:

eat apples cantaloupe bananas often

我想执行以下规则:

  1. 查找以eat开头并以often
  2. 结尾的字符串
  3. 如果字符串包含bananas,请将bananas替换为and especially bananas
  4. 如果字符串不包含香蕉,则不对字符串
  5. 执行任何操作

    我知道我可以使用这样的东西来制作字符串的一部分:

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

    我可以使用以下规则进行替换,假设存在bananas

       $1 and especially $2 $3
    

    但如果bananas不存在,这将产生奇怪的结果:

    输入

    eat apples cantaloupe often
    

    输出:

    eat apples cantaloupe and especially often
    

    我需要一个前瞻操作员吗?我读过this article但我仍然遇到麻烦。

2 个答案:

答案 0 :(得分:3)

尝试使用前瞻:

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

答案 1 :(得分: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