user2585000 user2585000 - 6 months ago 14
Perl Question

Perl regex: find second underscore and replace with a colon within a string

I seek your wisdom on this regex that's driving me crazy.

I want to replace the second underscore with a colon. That's it.

So far:

my $str = "bythepower_of_grayskull";
$str =~ s/.*?_.*?(_)/:/g;
print "$str\n";


Current output:
:grayskull


Desired output:
bythepower_of:grayskull

Answer

You need to put the capture group around the part that you want to keep, not the part you want to replace. Then use $1 in the replacement to copy the captured text.

$str =~ s/(.*?_.*?)_/$1:/;

And if there are only 2 underscores, you don't need the g modifier, since there's only one replacement being done.

Comments