in reply to regexp find last word

s/(fox.+)(fox.+?forest)/${1}the $2/;
Your regex matches at the earliest possible position. That weighs more than the laziness caused by the ?. Therefore you need to force it behind the first "fox".


holli, /regexed monk/

Replies are listed 'Best First'.
Re^2: regexp find last word
by Roy Johnson (Monsignor) on Mar 02, 2005 at 15:16 UTC
    You should ?-quantify the first parenthesized expression, so it works for one fox as well:
    s/(fox.+)?(fox.+?forest)/${1}the $2/

    Caution: Contents may have been coded under pressure.
Re^2: regexp find last word
by manav (Scribe) on Mar 02, 2005 at 15:39 UTC
    What happens in case of
    fox comes and the fox goes into forest
    The code given above will put a the in front of every last fox irrespective of if a the was already there or not.

    while(<DATA>) { s/(?<!the )fox(?!.*fox)/the fox/ ; print; } __DATA__ the fox comes and fox goes into forest fox comes and fox goes into forest the fox comes and the fox goes into forest fox comes and the fox goes into forest


    Manav
Re^2: regexp find last word
by Anonymous Monk on Mar 02, 2005 at 14:55 UTC
    That works, but it will not work if you have two foxes and two forests and you want to slap a /g on it.