Dear Monks,

I'm wondering if anyone can suggest an elegant solution to my regex substitution question. In the following:

my $greekReplace = "alpha|beta|chi|delta|epsilon|eta|gamma|hbar|kappa| +lambda|mu|nu|omega|phi|pi|psi|rho|sigma|tau|theta"; my $string = '3*mu'; $string =~ s/($greekReplace)/\\$1 /isg;
$string would end up as '3*\mu ' (note trailing space). This all works fine.

The issue is that I need to be able to NOT do the 'mu' substitution when 'mu' is prepended with 'a', as in 'amu'.

While I'm sure I can figure out a clunky way of doing the substitution with multiple levels of parentheses and memory variables, I'm wondering if there is a simple solution. I tried using 'a{0}mu' in the above string, but that doesn't work.

Here is some code I have used to test things I've tried:

#!/usr/bin/perl use strict; use warnings; my $greekReplace = "alpha|beta|chi|delta|epsilon|eta|gamma|hbar|kappa| +lambda|mu|nu|omega|phi|pi|psi|rho|sigma|tau|theta"; my %strings = ( mu => { valid => '\mu ' }, amu => { valid => 'amu' }, bmu => { valid => 'b\mu ' }, cmu => { valid => 'c\mu ' }, mud => { valid => '\mu d' }, '3*mu' => { valid => '3*\mu ' }, ); foreach my $string (sort keys %strings) { print "Before: '$string'; "; my $string2 = $string; $string2 =~ s/($greekReplace)/\\$1 /isg; print "After: '$string2' ; Should be: $strings{$string}->{valid}; +"; print $string2 eq $strings{$string}->{valid} ? "Passes\n" : "FAILS +\n"; } print "\n";

Thanks

Update: Thanks Monks....the negative look-behind does the trick!


In reply to Regex question by memnoch

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.