Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Replacing exactly the found instance in REGEX

by sathiya.sw (Monk)
on Dec 09, 2008 at 12:09 UTC ( [id://729140]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://729140]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-19 06:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found