matching and replacing workaround

Please support our Perl advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: May 2005
Posts: 45
Reputation: derekn is an unknown quantity at this point 
Solved Threads: 0
derekn derekn is offline Offline
Light Poster

matching and replacing workaround

 
1
  #1
Nov 8th, 2009
I want to search "The tree is in the yard" for the word "the", then replace the word "the" with "<font color=#FFFFFF>the</font>", which I currently do with "s/$searchstring/<font color=#FFFFFF>$searchstring</font>/gi;" BUT I want to preserve the case of the word, so that in this example the first word of the sentence would be white, but would have the capital T preserved. How can I do this?


Thanks,
Derek
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 33
Reputation: klactose is an unknown quantity at this point 
Solved Threads: 1
klactose klactose is offline Offline
Light Poster
 
1
  #2
Nov 9th, 2009
What you need to use is one of the back-reference variables, specifically you should use "$&" since you essentially want to reuse each occurrence of your search string

Give this a try
  1. $someText =~ s/$searchstring/<font color=#FFFFFF>$&<\/font>/gi;


Originally Posted by derekn View Post
I want to search "The tree is in the yard" for the word "the", then replace the word "the" with "<font color=#FFFFFF>the</font>", which I currently do with "s/$searchstring/<font color=#FFFFFF>$searchstring</font>/gi;" BUT I want to preserve the case of the word, so that in this example the first word of the sentence would be white, but would have the capital T preserved. How can I do this?


Thanks,
Derek
Reply With Quote Quick reply to this message  
Join Date: May 2005
Posts: 45
Reputation: derekn is an unknown quantity at this point 
Solved Threads: 0
derekn derekn is offline Offline
Light Poster
 
0
  #3
Nov 10th, 2009
Originally Posted by klactose View Post
What you need to use is one of the back-reference variables, specifically you should use "$&" since you essentially want to reuse each occurrence of your search string

Give this a try
  1. $someText =~ s/$searchstring/<font color=#FFFFFF>$&<\/font>/gi;

wow! So simple! This worked PERFECTLY! Thanks a million!
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 715 | Replies: 2
Thread Tools Search this Thread



Tag cloud for Perl
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC