Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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
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 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:
    JAZZxxJAZZJAZZxxJAZJAZZxxJAZZ JAZZaaJAZZJAZZaaaaaJAZZaaJAZZ

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

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-04-25 02:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (579 votes), past polls