Can I create a conditional find and replace with a regular expression?
I am trying to use an NginX substitution filter that allows regular expressions. I can get it to work in a basic way, i.e. replace phone
with telephone
, but I cannot get it to conditionally replace a line of text.
Here is the XML validation for validation:
eat apples cantaloupe bananas often
I would like to implement the following set of rules:
- Look for a line starting with
eat
and ending withoften
- If string contains
bananas
, replacebananas
withand especially bananas
- If the string does not contain bananas, do nothing with the string
I know I can use something like this to make parts of a string accessible:
/(eat.*)(bananas)?(.*often)/
I could use the following rule for replacement, assuming that is bananas
present:
$1 and especially $2 $3
But this will give an odd result if bananas
not:
entrance
eat apples cantaloupe often
output:
eat apples cantaloupe and especially often
Do I need an external operator? I have read this article but I am still having problems.
source to share
Alternative without view:
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
source to share