in reply to regex question

If you want to be precise on which field you are replacing, Anchoring(i.e Look-ahead and look-behind) would help. The following snippet illustrates how to replace the nth field.
This would replace the 2nd field
use strict; use warnings; my $str="1 2 3 4 5 6 7 8 9 10"; print "string is $str\n"; $str=~s/(?<=(\d\s){1})\d*/I am replaced/; print "string is $str";
Whereas if you want to replace 1st field use
$str=~s/(?<=(\d\s){0})\d*/I am replaced/;
Guesses for 10 th field ??
More info on look-ahead and look-behind here.

The world is so big for any individual to conquer

Replies are listed 'Best First'.
Re^2: regex question
by johngg (Canon) on Nov 12, 2007 at 11:25 UTC
    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

      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