Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: How do I replace a substring (if exists) with a different substring in a string?

by tachyon (Chancellor)
on Jul 20, 2001 at 15:43 UTC ( [id://98373]=note: print w/replies, xml ) Need Help??


in reply to How do I replace a substring (if exists) with a different substring in a string?

You can use a s/// regex like this:

my $str = "I have a dream"; my $find = "have"; my $replace = "had"; $find = quotemeta $find; # escape regex metachars if present $str =~ s/$find/$replace/g; print $str;

The quotemeta lets you find strings that contain regex meta characters and the /g at the end of the s/// does all occurances.

cheers

tachyon

  • Comment on Re: How do I replace a substring (if exists) with a different substring in a string?
  • Download Code

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-04-19 09:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found