Jim Jim - 3 months ago 6
Perl Question

How can I substitute double backslash with 1?

Having a string that has the backslash escaped i.e.

\\
how can I make it single backslash?

The
$string =~ s/\\/\/g;
does not work.

Jan Jan
Answer

You need four backslashes as the backslash itself needs to be escaped as well:

$string =~ s/\\\\/\\/g

See a demo on regex101.com.


A complete example in Perl:

my $string = 'this is a double backslash: \\\\';
print $string . "\n";
$string =~ s/\\\\/\\/g;
print $string;

See the demo on ideone.com.