user2585000 user2585000 - 1 year ago 93
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:

Desired output:

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download