CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
conditional find+replace using regex

 



voltaire
New User

Feb 27, 2005, 5:00 AM

Post #1 of 5 (4424 views)
conditional find+replace using regex Can't Post

 Is there a one-line regex way to specify a replacement in a string if certain conditions need to be met...

eg

if i had the string
a b a b a b <tag> a b a b </tag> a b <tag> a b a b </tag> a b
and i wanted to replace all 'a' with 'z' iff they are enclosed within a <tag></tag> pair (and i dont mean the first opening tag and the last closing tag)
ie
a b a b a b <tag> z b z b </tag> a b <tag> z b z b </tag> a b

There are ways to do it using several lines of string manipulation, but i was wondering if there are some neat regex tricks to specify the condition neatly?


eg
hoping for a solution of the form
$string =~ s/x/y/
where x and y describe/fulfill the condition (if it's even possible)


many thanks


MrPJ
User

Feb 27, 2005, 9:08 AM

Post #2 of 5 (4420 views)
Re: [voltaire] conditional find+replace using regex [In reply to] Can't Post

Here's one way...


Code
$string =~ s|<tag>(.+?)</tag>|my $temp = $1; $temp =~ tr/a/z/; $temp;|ge;



KevinR
Veteran


Feb 27, 2005, 12:08 PM

Post #3 of 5 (4417 views)
Re: [MrPJ] conditional find+replace using regex [In reply to] Can't Post

if you want the tags to remain in the string:


Code
$test =~ s|<tag>(.+?)</tag>|my $temp = $1; $temp =~ tr/a/z/; "<tag>$temp</tag>";|ge;


if not, MrPJ's suggestion works perfect! Cool
-------------------------------------------------


voltaire
New User

Feb 27, 2005, 12:35 PM

Post #4 of 5 (4416 views)
Re: [KevinR] conditional find+replace using regex [In reply to] Can't Post

thanks people.

i appreciate it


MrPJ
User

Feb 27, 2005, 2:59 PM

Post #5 of 5 (4413 views)
Re: [KevinR] conditional find+replace using regex [In reply to] Can't Post


In Reply To
if you want the tags to remain in the string:


Good spot =)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives