in reply to Re: regex question
in thread regex question

The problem with the approach you advocate here is that look-behind assertions are fixed width so you can't do something like (?<=\d+\s). If you declare the string like this

my $str="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15";

how do you replace the 12th field?

I'm all for look-around assertions but I don't think they are suited to this particular problem.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^3: regex question
by convenientstore (Pilgrim) on Nov 12, 2007 at 15:55 UTC
    I thought of look behind but decide against it since field 9 can and will have dynamic variables..

    still working on this.
      if you capture something by () in regex and you get $1,$2,$3 and so on, why can't you just do
      s/$2/something/
      In this script, it's doing it but it's changing the value rather than position. What i mean is,
      [root@myserver tmp]# cat perl.test #!/usr/bin/perl -w use strict; my $string = "123 123 345"; if ("$string" =~ /(\d+)\s+(\d+)\s+(\d+)/) { $string =~ s/$2/something/; print "$string\n"; } [root@myserver tmp]# ./!$ ./perl.test something 123 345
      I wanted this to change the value of position $2, Therefore wanted to see
      123 something 345
        That happens because your second capture, held in $2, is "123" so in your substitution inside the if $2 is interpolated to give s/123/something/, which runs quite happily and replaces the first occurence of "123" in $string. Had your string been "987 123 345" your code would have given the result you wanted but only as a side effect of your error. You could do it like this (not tested)

        use strict; use warnings; my $string = q{123 123 345}; if ( $string =~ s{^(\d+\s+)(?:\d+)(\s+\d+)}{$1something$2} ) { print qq{Succeeded\n$string\n}; } else { print qq{Failed\n$string\n}; }

        I hope this makes things a bit clearer.

        Cheers,

        JohnGG