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

Hello,
I have the following code:
$string = "useridagohiluserid>traderidagohiltraderidjiagohilji"; if ($string =~ /traderid(.*?)traderid/sig) { $string =~ s/$1/myword/ ; } print "$string\n" ;
I would expect it to print the below :
useridagohiluserid>traderidmywordtraderidjiagohilji

but it prints the below:
useridmyworduserid>traderidagohiltraderidjiagohilji

Because "agohil" appears BEFORE as well and not just between "traderid" and "traderid", the first instance is replaced. I would like the replacement to be done only between the two 'traderid' instances.
Thanks!

Replies are listed 'Best First'.
Re: Replacing exactly the found instance in REGEX
by JavaFan (Canon) on Dec 09, 2008 at 11:30 UTC
    Then use s///:
    $string =~ s/(traderid)(.*?)(traderid)/${1}myword${3}/s;

      To extend what JavaFan is saying, you can use the s/// operator in place of the test and substitute. In your example there doesn't seem to be any reason to test the string first.

      G. Wade
Re: Replacing exactly the found instance in REGEX
by sathiya.sw (Monk) on Dec 09, 2008 at 12:09 UTC
    A simple change in your code would achieve this,
    $string = "useridagohiluserid>traderidagohiltraderidjiagohilji"; if ($string =~ /traderid(.*?)traderid/sig) { $string =~ s/(?<=traderid)$1(?!=traderid)/myword/ ; } print "$string\n" ;

    Change which am asking you to do is simple, is called as lookarounds in regex.

    (?<=TEXT) --> mean look behind.
    (?!=TEXT) --> mean look ahead.
    So you wanted traderid to be presented in both the side, by confirming that again in the substitution you can achieve it.
    Sathiya

      You have made a slight mistake with your look-ahead syntax.

      (?=pattern) Positive look-ahead match is followed by pattern
      (?!pattern) Negative look-ahead match is not followed by pattern
      (?<=pattern) Positive look-behind match is preceeded by pattern
      (?<!pattern) Negative look-behind match is not preceeded by pattern

      Note that for look-behind assertions the pattern can not be of variable width.

      I hope this is of interest.

      Cheers,

      JohnGG

        Thanks a lot for your inputs. For now, I am able to continue by using the syntax in the first reply. I will also try and understand the lookahead and lookbehind assertions and their usage.
        Regards,
        inquis