我希望能够对字符串执行正则表达式,以便在双引号之前添加反斜杠,只有在它之前没有反斜杠时才会这样。因此函数(例如regex_string)将具有输出 -
$my $string_1 = 'A "sentence';
regex_string($string_1); # Would equal 'A \"sentence'. A backslash was added as one was not present.
$my $string_2 = 'A \"sentence';
regex_string($string_1); # Would equal 'A \"sentence'. A backslash is not added because one already existed.
任何人都可以帮助正则表达式看起来如何?感谢
答案 0 :(得分:2)
以下正则表达式将匹配所有双引号"
,前面没有反斜杠。用\\"
替换匹配的双引号将为您提供所需的输出。
正则表达式:
(?<!\\)(")
替换字符串:
\\\1
#!/usr/bin/perl
use strict;
use warnings;
my @strings = ('A "sentence', 'A\"sentence', '"A sentence');
for my $str(@strings) {
$str =~ s/(?<!\\)(")/\\$1/g;
print $str, "\n";
}
或者正则表达式就像$str =~ s/(?<!\\)"/\\"/g;
<强>输出强>
A \"sentence
A\"sentence
\"A sentence
答案 1 :(得分:1)
正则表达式可能是:s/[^\\]"|^"/\\"/g
。
它会查找\
"
不同的任何字符
use strict;
use warnings;
my @strings = ('A "sentence', 'A\"sentence', '"A sentence');
for my $str(@strings) {
$str =~ s/[^\\]"|^"/\\"/g;
print $str, "\n";
}
打印:
A\"sentence
A\"sentence
\"A sentence
答案 2 :(得分:1)
它会将\
放在"
之前,并且反斜杠尚未到位,
$string =~ s|(?<! \\)(?= ")|\\|xg;
答案 3 :(得分:0)
答案 4 :(得分:0)
反斜杠可以逃脱吗?
因此字符串A \\"sentence
需要有一个额外的反斜杠来逃避双引号?
如果是这样,那么以下实现将起作用:
use strict;
use warnings;
while (my $str = <DATA>) {
$str =~ s/\\.(*SKIP)(*FAIL)|(?=")/\\/g;
print $str;
}
__DATA__
A "sentence
A\"sentence
"A sentence
A \\"sentence
A \\\"sentence
输出:
A \"sentence
A\"sentence
\"A sentence
A \\\"sentence
A \\\"sentence