Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular Expression- contextual replacement

Status
Not open for further replies.

dleathe07

Programmer
Joined
Mar 15, 2008
Messages
3
Location
US
Hi, would it be possible to match a chunk in a file, and then replace only a portion (a phrase) of it?

For example:

$a = "<start>op3 and op and op2</start>"

I need to do things sequentially:
1. Match <start>.+?</start>
2. Replace "op" contained with "op1"

The end result should look like:
$a = "<start>op3 and op1 and op2 </start>"

I tried $a =~ s/<start>(op)[^0-9]</start>/op1/

I keep replacing the entire <start> block instead only a part of it. Does Perl have something like a contextual replacement or conditional replacement, or maybe nested regular exps?

Thanks guys.
 
Is this school work? I ask because the regexp you posted will do nothing, in fact, it should cause perl to complain about a syntax error and terminate, which makes me suspicious you never tried it or that it is not the code you actually tried to use.

Here you will find two regexp tutorials:


Here is a free book with a regexp chapter (5):


Or wait and someone will probably post the exact code you need to match the pattern you posted.



------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Not school work, not sure why you'd think that. The regexp I posted was just the general idea. I'm no beginner with regular expressions. I'm looking for the general method of preforming replacement selectively, or maybe nested regexp. I was hoping one of the Perl experts here would know, or advise on an alternative.
 
Nvm, I figured it out. Thanks anyways.
 
Well, it's never a good idea to post invalid code and expect anyone here to know its a general concept and not the root cause of your problem. Not sure why you would think that. ;)

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top