Perl regex replace?
Why does this work:
$my_str=~s/://g;
But this does not:
$my_str=~s/:://g;
I have a string that looks something like this: ::this:is:my:string
and I need to remove the ::
but not touch the开发者_开发知识库 :
.
Works fine for me:
$ echo "::this:is:my:string" | perl -ne "s/:://g; print;"
this:is:my:string
Are you sure you don't have any typos in your code? And that this substitution is in fact the problem? The following program worked for me:
my $var = '::a:b:c::';
print "$var\n";
$var =~ s/:://g;
print "$var\n";
Output:
$ perl test.pl
::a:b:c::
a:b:c
$
Edit to add a couple suggestions:
- Print the variable immediately before and after the substitution.
- No immediately the problem at hand, but if you only need to remove the :: at the beginning of the string, you may want to add a ^ to the regex to indicate that.
There are two things I can think of that would cause $my_str =~ s/:://g;
fail:
$my_str
doesn't contains what you say it contains.pos($my_str)
is set.
To make sure $my_str
contains what you think it does, you could use Data::Dumper, but make sure to do $Data::Dumper::Useqq = 1;
before using Dumper
.
But first, make sure you aren't doing something like
if ($my_str =~ /.../g) {
...
$my_str =~ s/:://g;
...
}
if ($my_str =~ /.../g)
is a common mistake, and it could cause this problem. (I don't know why since it doesn't even make sense conceptually.) If so, get rid of the g
in the if
condition.
精彩评论