in reply to Replacing exactly the found instance in REGEX

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

Replies are listed 'Best First'.
Re^2: Replacing exactly the found instance in REGEX
by johngg (Canon) on Dec 09, 2008 at 12:52 UTC

    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