简体   繁体   English

Perl - 如何将转义序列放入字符串?

[英]Perl - how to put escape sequence into string?

I am converting one form of regex to Perl-compatible regex. 我正在将一种形式的正则表达式转换为Perl兼容的正则表达式。 I need to replace all occurrences of %s to \\s , so I am doing: 我需要将所有出现的%s替换为\\s ,所以我这样做:

$s =~ s/(?<!%)%s/\s/g;

But it gives me error: Unrecognized escape \\s passed through at .... . 但是它给了我错误: Unrecognized escape \\s passed through at .... Actually I am understanding where the problem is, so probably I can't convert to string some unknown escape sequence. 其实我在理解问题所在,所以我可能无法转换为字符串一些未知的转义序列。 But how do I bypass this thing? 但是我该如何绕过这个东西呢?

You just need to escape the \\, like: 你只需要逃脱\\,就像:

$s =~ s/(?<!%)%s/\\s/g;

For example 例如

my $s = "this is a %s test with two %s sequences, the last one here %%s not changed";
$s =~ s/(?<!%)%s/\\s/g;
print "$s\n";

prints 版画

this is a \s test with two \s sequences, the last one here %%s not changed

(not sure if you need the %%s to end up being just %s, if so it needs a little tweak or a second regexp to do that). (不确定你是否需要%% s最终只是%s,如果是这样,它需要一点调整或第二个正则表达式来做到这一点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM