Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
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##

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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 chanting in the Monastery: (3)
As of 2023-03-24 05:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (60 votes). Check out past polls.

    Notices?