Member Avatar for diafol

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:

'/(?<!io)di/i'

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

BTW:

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'.

/?EDIT

'/(?<!o)di/i'

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.

#!/usr/bin/perl
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
Member Avatar for diafol

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

Will get back to you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.