Hi all, am using a regex (in php), but I'm all confused.

I'm trying to replace a string ('di') with 'deu'. SImple enough, but I don't want a replacement if 'di' is preceded by 'io' as in 'iodine', 'iodic', 'iodide' etc.

This is what I have:


It works fine for everything, but unfortunately it doesn't stop the 'iodi' from becoming 'iodeu'. Any light on this would great. Thank you.


I'm actually trying to create a chemical translation function, which means 'di' as in 'two of' should change to 'deu', but everything else should not change.
Unfortunately, I've found '..thiodi..' which should change to '..thiodeu..', just to complicate matters.

So 'di' and 'thiodi' should be replaced but not 'iodi'.



This works as expected.

Rather than struggle to compose one regex that does all the substitution I would use two regexes. I find it easier to understand and change if necessary.

use strict;
use warnings;

my @words = qw(iodine Thiodi number dix Iodic iodide);

foreach my $word(@words){
    $word =~ s/(?<!io)di/deu/i;#Replace di with deu unless preceded by io
    $word =~ s/(?=thio)di/deu/i;#Replace di with deu if preceded by thio
    print "$word ";
print "\n"; #iodine Thiodi number deux Iodic iodide

Thanks d5e5, I'll give it a go. I'll need to change code to php but looks strightforward.

Will get back to you.

This question has already been answered. Start a new discussion instead.