in reply to Regex that will append to end of same line

Oops ... my original post was intended to
be used with sed, or vi style regex.

In perl you could do ...

while(<>) { s/(^1.*)/\1,P/g; print; }


Sorry about the confusion


--
Its like a dog that can sing and dance.
It's remarkable because it can do it.
Not that it can do it well.

Replies are listed 'Best First'.
Re: Re: Regex that will append to end of same line
by Juerd (Abbot) on Jan 04, 2002 at 02:05 UTC

    In Perl, we use $1 instead of \1 in the substitution string. The right hand side is just another interpolated string.

    From perlop:

    It is at this step that "\1" is begrudgingly converted to $1 in the replacement text of "s///" to correct the incorrigible sed hackers who haven't picked up the saner idiom yet. A warning is emitted if the "use warnings" pragma or the -w command-line flag (that is, the $^W variable) was set.

    From Jeffrey E. F. Friedl's great book Mastering Regular Expressions:

    The Perl manpage makes a concerted effort to point out that \1 is not available as a backreerence outside of a regex. (Use the variable $1 instead.) \1 is much more than a simple notational convenience - the variable $1 refers to a string of static text matched during some previously completed successful match. On the other hand, \1 is a true regex metacharacter to match text similar to that matched within the first parenthesized subexpression (...)

    perl -we's//\1/' 2>&1 |splain

    \1 better written as $1 at -e line 1 (#1)
    (W syntax) Outside of patterns, backreferences live on as variables. The use of backslashes is grandfathered on the right-hand side of a substitution, but stylistically it's better to use the variable form because other Perl programmers will expect it, and it works better if there are more than 9 backreferences.

    And dot star (.*) is bad in this case.

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

      Thanks!

      I knew I'd learn something from Perlmonks!

      --
      Its like a dog that can sing and dance.
      It's remarkable because it can do it.
      Not that it can do it well.