$str = '\good\day';
$str =~ s#\\#\\\\#g;
print $str;
结果是:\\ good \\ day
何时
my $str = '\good\day\';
我想得到结果\\ good \\ day \\
正则表达式$str =~ s#\\#\\\\#g;
没有给出预期的结果。
你能帮帮我吗?
答案 0 :(得分:2)
你的代码甚至不应该编译。它应该给出错误:
Can't find string terminator "'" anywhere before EOF
您需要在单引号字符串声明中转义第二个反斜杠。就像你必须使用反斜杠转义单引号一样,你还需要在单引号字符串的末尾转义反斜杠。
此代码将按您的意图运行:
my $str = '\good\day\\';
print "From: ", $str, "\n";
$str =~ s#\\#\\\\#g;
print " To: ", $str, "\n";
输出:
From: \good\day\
To: \\good\\day\\