Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a conditional find & replace with a regular expression?

Tags:

regex

nginx

I am using trying to a NginX substitution filter which allows the use of regular expressions. I can get it working in a basic manner, i.e. replacing phone with telephone, but I can't seem to get it to conditionally replace a string of text.

Here is a check of XML for examination:

eat apples cantaloupe bananas often

I would like to perform the following set of rules:

  1. Look for a string starting with eat and ending with often
  2. If the string contains bananas then replace bananas with and especially bananas
  3. If the string does not contain bananas do not do anything to the string

I know that I can use something like this to make parts of the string available:

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

I could use the following rule to do the replacement assuming bananas is present:

   $1 and especially $2 $3

But this will give an odd result if bananas is not present:

input

eat apples cantaloupe often

output:

eat apples cantaloupe and especially often

Do I need a look ahead operator? I've read this article but I'm still having trouble.

like image 419
cwd Avatar asked Apr 25 '26 15:04

cwd


2 Answers

Try using a look ahead:

/(?=.*eat.*bananas.*often) bananas/
like image 180
Bohemian Avatar answered Apr 28 '26 08:04

Bohemian


Alternative without lookahead:

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
like image 41
guido Avatar answered Apr 28 '26 08:04

guido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!