Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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

( #98357=categorized question: print w/ replies, xml ) Need Help??
Contributed by kommesel on Jul 20, 2001 at 13:44 UTC
Q&A  > strings


Answer: How do I replace a substring (if exists) with a different substring in a string?
contributed by tachyon

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

Answer: How do I replace a substring (if exists) with a different substring in a string?
contributed by davorg

With appropriate use of index, length and substr.

And remember that substr can be used as an lvalue.

Answer: How do I replace a substring (if exists) with a different substring in a string?
contributed by harangzsolt33

Another way to do it is split the string at every occurrence of $find and then join it together using the new pattern $replace like this:

$string = join( $replace, split($find, $string) );
I think, this is a much neater way to do it, however I do not know how fast it is or how much more memory it uses. I have found that in JavaScript, this method works faster than the regular replace() method. Generally, working with arrays in JavaScript is always faster than working with strings. Btw could somebody do a benchmark on this to see how it compares to the other solutions?
Answer: How do I replace a substring (if exists) with a different substring in a string?
contributed by dkubb

You can use substr, length, and index inside a while loop to do what you want:

my $string = '01234567890'; my $find = '0'; my $replace = 'a'; my $pos = index($string, $find); while ( $pos > -1 ) { substr( $string, $pos, $length( $find ), $replace ); $pos = index( $string, $find, $pos + length( $replace )); }

Benchmarked, this is about 15-20% faster than a s///g regex.

IMHO, unless blazing speed is really important, you can't beat the following for readability:

  $string =~ s/\Q$find\E/$replace/g;
Answer: How do I replace a substring (if exists) with a different substring in a string?
contributed by harangzsolt33

I wrote a little program that runs a million string replace operations using the three methods that have been suggested here so far, and it displays how many seconds it takes to run each replace operation. (I am using tinyperl 5.8 on Windows XP Pro SP2. And I am a beginner Perl programmer.)

As it turns out, if the length of the resulting string is longer than the original after the replacement, then it takes longer to do the replacement. Btw, the regexp has been the fastest method. The split/join method was average. And the substr method was the slowest! It was so slow that I had to abort the program after it replaced 1 million "HelloWorld" strings to "XXWorld." It took more than an hour! Anyway, here is the code:

This program will perform 1000000 string replace operations and print the number of seconds it takes to complete each. Testing string replace method #1. Replace 'H' --> 'X' 0 second(s) Replace 'Hello' --> 'XX' 0 second(s) Replace 'Hello' --> '' 1 second(s) Replace 'Hel' --> 'XXXXXX' 14 second(s) Replace 'HelloWorld' --> 'XXXXXXXXXXXXX' 14 second(s) Testing string replace method #2. Replace 'H' --> 'X' 5 second(s) Replace 'Hello' --> 'XX' 2 second(s) Replace 'Hello' --> '' 1 second(s) Replace 'Hel' --> 'XXXXXX' 16 second(s) Replace 'HelloWorld' --> 'XXXXXXXXXXXXX' 1 second(s) Testing string replace method #3. Replace 'H' --> 'X' 1 second(s) Replace 'Hello' --> 'XX' 4928 second(s) Replace 'Hello' --> '' ################################################## #PROGRAM STARTS HERE: use strict; use warnings; # See: # http://www.perlmonks.org/?node_id=98357 my $T; my $str; my $find = ""; my $replace = ""; my $REPEAT = 1000000; my $METHOD = 1; print "This program will perform $REPEAT string replace operations\n"; print "and print the number of seconds it takes to complete each.\n"; # RUN TESTS for ($METHOD = 1; $METHOD <= 3; $METHOD++) { print "\nTesting string replace method #$METHOD.\n"; RunTest("H", "X"); RunTest("Hello", "XX"); RunTest("Hello", ""); RunTest("Hel", "XXXXXX"); RunTest("HelloWorld", "XXXXXXXXXXXXX"); } ##################################### sub RunTest { if (@_ != 2) {return;} ($find, $replace) = @_; $| = 1; # Disable buffering $str = 'HelloWorld' x $REPEAT; my $PADDING1 = ' ' x (13 - length($find)); my $PADDING2 = ' ' x (13 - length($replace)); print "Replace '$find'$PADDING1--> '$replace'$PADDING2"; # This method was suggested by tachyon. if ($METHOD == 1) { $find = quotemeta $find; # escape regex metachars if present $T = time; # measure time at the start. $str =~ s/$find/$replace/g; printTime(); # measure time at the end. } # This method was suggested by harangzsolt33 if ($METHOD == 2) { $T = time; # measure time at the start. $str = join( $replace, split($find, $str) ); printTime(); # measure time at the end. } # This method was suggested by davorg. if ($METHOD == 3) { $T = time; # measure time at the start. my $pos = index($str, $find); while ( $pos > -1 ) { substr( $str, $pos, length( $find ), $replace ); $pos = index( $str, $find, $pos + length( $replace )); } printTime(); # measure time at the end. } return; } ########################### sub printTime { my $DIFF = (time - $T); my $PADDING = ' ' x (3 - length($DIFF)); print "$PADDING $DIFF second(s)\n"; } ###########################

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others wandering the Monastery: (4)
    As of 2016-06-26 21:29 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      My preferred method of making French fries (chips) is in a ...











      Results (331 votes). Check out past polls.