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:
Replacing all occurrences of something in a part of a string

 



evgen-i
New User

Apr 15, 2010, 1:29 AM

Post #1 of 2 (2625 views)
Replacing all occurrences of something in a part of a string Can't Post

Hi,

I wonder if it is possible to write a regular expression that replaces all occurrences of something (e.g. whitespace), but not in the whole string, but a part of a string that is identified by some matched characters.

In my particular example, I would like to replace all spaces with underscores between an opening and a closing parenthesis (possibly with multiple occurrences of (...) in the line).

"bla bla (this is some stuff in parens) bla (and again) bla" -> "bla bla (this_is_some_stuff_in_parens) bla (and_again) bla"

Thanks much!


roolic
User

Apr 15, 2010, 4:21 AM

Post #2 of 2 (2622 views)
Re: [evgen-i] Replacing all occurrences of something in a part of a string [In reply to] Can't Post


Code
my $str = 'bla bla (this is some stuff in parens) bla (and again) bla'; 

while( $str =~ /\(([^\)]*?\s+[^\)]*?)\)/ ){
my $substr = $newsubstr = $1;
$newsubstr =~ s/\s+/_/g;
# uncomment to see the progress
# print "old:'$substr'\nnew: '$newsubstr'\n";
$str =~ s/\($substr\)/\($newsubstr\)/g;
}

print $str;


 
 


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

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