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 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;
|
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!
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
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|