Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
Just another Perl shrine
 
PerlMonks  

Re: Regex: Case insensitive search but case sensitive replace

by ehdonhon (Curate)
on Nov 17, 2003 at 11:54 UTC ( #307631=note: print w/ replies, xml ) Need Help??


in reply to Regex: Case insensitive search but case sensitive replace

If you use the /i switch in combination with 's///', it will capture any case permutation of whatever it is you are replacing, and if you use that captured text, it will appear in the exact same case permutation as it was captured. This will work no matter what you are trying to capture.

while ( chomp( my $line = <DATA> ) ) { $line =~ s/(Fred)/"$1"/i; print "$^C root@who1# perl while ( my $line = <DATA> ) { $line =~ s/(Fred)/"$1"/i; print $line; } __DATA__ Hello, my name is FRED! fREd went to the store. Nobody was home, except for freD.

Output:

Hello, my name is "FRED"!
"fREd" went to the store.
Nobody was home, except for "freD".

You mention in a later post that you are looking for something more generic that will work for anything, not just names. Perhaps this is what you are looking for?

my $tag = 'jane'; while ( <DATA> ) { s/($tag)/##$1##/i; # you might also want a /g here as well. print; } __DATA__ - John is following jane - John is following Jane

Output:

- John is following ##jane##
- John is following ##Jane##


Comment on Re: Regex: Case insensitive search but case sensitive replace
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2014-04-17 05:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (439 votes), past polls