我正在尝试使用NginX替换过滤器,它允许使用正则表达式。我可以以基本的方式使用它,即用phone
替换telephone
,但我似乎无法有条件地替换一串文本。
这是检查XML的检查:
eat apples cantaloupe bananas often
我想执行以下规则:
eat
开头并以often
bananas
,请将bananas
替换为and especially bananas
我知道我可以使用这样的东西来制作字符串的一部分:
/(eat.*)(bananas)?(.*often)/
我可以使用以下规则进行替换,假设存在bananas
:
$1 and especially $2 $3
但如果bananas
不存在,这将产生奇怪的结果:
输入
eat apples cantaloupe often
输出:
eat apples cantaloupe and especially often
我需要一个前瞻操作员吗?我读过this article但我仍然遇到麻烦。
答案 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