anna_black has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I need to do a simple command line substitution of a string, but I'm obviously making some mistake, as it doesn't work:

> echo "Hello Dolly" | perl -lpe "s/l(lo)/$1/" He Dolly

I'm probably missing something completely silly, but I can't understand why the $1 doesn't capture the lo in the parentheses... (I want the output to be Helo Dolly)

Thanks a lot!

Replies are listed 'Best First'.
Re: Regex capturing
by FunkyMonk (Bishop) on Apr 06, 2009 at 12:00 UTC
    It's all down to quoting. On *nix systems you need to use single quotes around your Perl to avoid the shell trying to expand $1:
    echo "Hello Dolly" | perl -lpe 's/l(lo)/$1/' #Helo Dolly

Re: Regex capturing
by manoj_speed (Prior) on Apr 06, 2009 at 13:21 UTC

    In Unix system the double quotes will expand the $1, so you may not get the actual output that you required.

    You can use single quotes or escape the $1(in double quotes) to solve this.

    But you can also achieve this using this simple method also.(substitute loo with lo (for this requirement/string. But it won't be nice for bigger match)).

    --
    The wisest mind has something yet to learn.
Re: Regex capturing
by Grey Fox (Chaplain) on Apr 06, 2009 at 14:36 UTC
    Hi Anna;
    There is a great php based tool called My REGEX Tester for checking out and experimenting with your REGEX.
    I have a link to it in Found new online Regex tool.
    Plus there is a nice website called Regular-Expressions Quickstart. This teaches all of the basics of REGEX.

    Hope this helps.

    -- Grey Fox
    "We are grey. We stand between the darkness and the light" B5
A reply falls below the community's threshold of quality. You may see it by logging in.