3

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

这是检查 XML 的检查:

eat apples cantaloupe bananas often

我想执行以下规则集:

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

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

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

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

   $1 and especially $2 $3

bananas但是,如果不存在,这将给出一个奇怪的结果:

输入

eat apples cantaloupe often

输出:

eat apples cantaloupe and especially often

我需要前瞻运算符吗?我已经阅读了这篇文章,但我仍然遇到问题。

4

2 回答 2

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
于 2013-01-22T00:41:38.777 回答
3

尝试使用前瞻:

/(?=.*eat.*bananas.*often) bananas/
于 2013-01-22T00:28:27.913 回答