Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

A challenging problem in perl regular expression

by yai (Initiate)
on Jan 08, 2009 at 01:06 UTC ( #734772=perlquestion: print w/replies, xml ) Need Help??
yai has asked for the wisdom of the Perl Monks concerning the following question:

Can anyone help me to solve this problem? I am looking for a single perl regular expression that can replace all occurrentcs of not 'JAZZ' with 'a'. For example, "aJAZJAZZa" should be change to "aaaaJAZZa" I tried to use lookaround feature in Perl but I can't find a solution yet. I sill can not disambiguate between the last 2 'Z' in 'JAZZ'.
  • Comment on A challenging problem in perl regular expression

Replies are listed 'Best First'.
Re: A challenging problem in perl regular expression
by ikegami (Pope) on Jan 08, 2009 at 01:17 UTC

    What makes it hard to do in a regexp is that "JAZJ" is not "JAZZ", yet you don't want to replace it. This is not the job of a regexp.

    Two ways:

    • s/ . (?<!J(?=AZZ)) (?<!JA(?=ZZ)) (?<!JAZ(?=Z)) (?<!JAZZ) /a/xgs;
    • s/~/a/g; s/JAZZ/~/g; s/[^~]/a/g; s/~/JAZZ/g;
    • s/(JAZZ|.)/$1 eq 'JAZZ' ? $1 : 'a'/egs;
    • s/(JAZZ)|./defined($1) ? $1 : 'a'/egs;
    • s/((?:JAZZ)*)./$1a/gs;

    Update: Or more.

      ikegami, thanks a lot. but the last one doesn't work if there is more than 1 'JAZZ' in a string. I tried on "JAZZxxxxJAZZ" but the result was "JAZZaaaaaaaa".

        It does work if there's more than one 'JAZZ' in the string, but it doesn't work if there's one at the end of the string. Scratch that one.

        The best test case is probably "JAZZxxJAZZJAZZxxJAZJAZZxxJAZZ"

Re: A challenging problem in perl regular expression
by jwkrahn (Monsignor) on Jan 08, 2009 at 05:45 UTC

    Also, another way to do it:

    $ perl -le' my $string = "JAZZxxJAZZJAZZxxJAZJAZZxxJAZZ"; print $string; $string = join "JAZZ", grep [ tr//a/c ], split /JAZZ/, $string, -1; print $string; ' JAZZxxJAZZJAZZxxJAZJAZZxxJAZZ JAZZaaJAZZJAZZaaaaaJAZZaaJAZZ
Re: A challenging problem in perl regular expression
by Albannach (Prior) on Jan 08, 2009 at 05:03 UTC
    How about:
    $_='JAZZxxJAZZJAZZxxJAZJAZZxxJAZZ'; print $_,$/; s/(.*?)(JAZZ)/('a'x length $1) . $2/ge; print
    which gives:

    I'd like to be able to assign to an luser

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://734772]
Approved by ikegami
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (17)
As of 2016-10-26 13:19 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (340 votes). Check out past polls.