in reply to Negating a regexp

It's negative look ahead assertion time again:

#!/usr/bin/perl -w use strict; while (<DATA>) { s/(.*ing)((?!bob|fred|bill)\w+?)(more)/$1HIT$3/; print $_; } __DATA__ somestringbobmoremore somestringfredmoremore somestringbillmoremore somestringtedmore

Prints:

somestringbobmoremore somestringfredmoremore somestringbillmoremore somestringHITmore

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Negating a regexp
by ikegami (Patriarch) on Jan 31, 2006 at 22:49 UTC
    Not quite. I have a feeling more is not actually more. If so, this may fail. For example, if more is really less,
    somestringbilless
    doesn't get changed to
    somestringHITless.

      Modified regex to accomodate bil:

      #!/usr/bin/perl -w use strict; while (<DATA>) { s/(.*ing)((?!bob|fred|bill(?!ess))\w+?)(more|less)/$1HIT$3/; print $_; } __DATA__ somestringbobmoremore somestringfredmoremore somestringbillmoremore somestringtedmore somestringbilless

      Prints:

      somestringbobmoremore somestringfredmoremore somestringbillmoremore somestringHITmore somestringHITless

      DWIM is Perl's answer to Gödel
        Thanks to everyone for working solutions provided. To further refine the OP, as I tried to simplify for the sake of clarity : Consider :
        #!/usr/bin/perl -w use strict; while ( <DATA> ) { s/ angle brackets between element pairs / instead make square +bracketed / print $_ . "\n"; } __DATA__ <sometag> my data here </sometag> <anothertag> further text </anothertag> <furthertag> not good as contains <this> in angle brackets </furtherta +g> <byetag> another possibility is <more> <than> one <angle pairs> in her +e </byetag>
        As I can no longer specify (more|less) as fixed patterns ( as per ikegami hunch ) Im again struggling to apply what is demonstrated to my actual data... Required output :
        <sometag> my data here </sometag> <anothertag> further text </anothertag> <furthertag> not good as contains [this] in angle brackets </furtherta +g> <byetag> another possibility is [more] [than] one [angle pairs] in her +e </byetag>

      It is just what OP asked for. If OP wanted to match more or less then:

      s/(.*ing)((?!bob|fred|bill)\w+?)(more|less)/$1HIT$3/

      does the trick.

      Note that OP says:

      Im getting stuck specifying 'not' - OK with a caracter class, ( ie ^some chars ) - but not when using parenthesis to define multiple 'words'

      DWIM is Perl's answer to Gödel
        Nope, doesn't work.
        #!/usr/bin/perl -w use strict; while (<DATA>) { s/(.*ing)((?!bob|fred|bill)\w+?)(more|less)/$1HIT$3/; print $_; } __DATA__ somestringbilless
        outputs
        somestringbilless
        and not
        somestringHITless