[英]How do you match \'
I need a regex to match \' <---- literally backslash apostrophe.我需要一个正则表达式来匹配\' <---- 字面上的反斜杠撇号。
my $line = '\'this';
$line =~ s/(\o{134})(\o{047})/\\\\'/g;
$line =~ s/\\'/\\\\'/g;
$line =~ s/[\\][']/\\\\'/g;
printf('%s',$line);
print "\n";
All I get out of this is我从中得到的只是
'this
When what I want is当我想要的是
\\'this
This occurs whether the string is declared using '
or "
. This was a test script for tracking down a file parsing bug. I wanted to confirm that the regex was working as expected.无论字符串是使用'
还是"
声明的,都会发生这种情况。这是一个用于跟踪文件解析错误的测试脚本。我想确认正则表达式是否按预期工作。
I don't know if when the backslash apostrophe is parsed by the regex it is not treated as 2 characters, but is instead treated as an escaped apostrophe.我不知道当正则表达式解析反斜杠撇号时,它是否不被视为 2 个字符,而是被视为转义的撇号。
Either way.无论哪种方式。 what is the best way to match \'
and print out \\'
?匹配\'
并打印出\\'
的最佳方法是什么? I don't want to escape any other back slashes or apostrophes and I can't change the text I am parsing, just the way it is handled and outputted.我不想转义任何其他反斜杠或撇号,我不能改变我正在解析的文本,只是它的处理和输出方式。
s/\\'/\\\\'/g
All three of your patterns match a backslash followed by a quote, the above being the simplest.您的所有三个模式都匹配一个反斜杠,后跟一个引号,上面是最简单的。
Your testing was in vain because your string doesn't contain any backslashes.您的测试是徒劳的,因为您的字符串不包含任何反斜杠。 Both string literals "\'this"
(from earlier edit) and '\'this'
(from later edit) produce the string 'this
.字符串文字"\'this"
(来自之前的编辑)和'\'this'
(来自后来的编辑)都会产生字符串'this
。
say "\'this"; # 'this
say '\'this'; # 'this
To produce the string \'this
, you could use either of the following string literals (among others):要生成字符串\'this
,您可以使用以下任一字符串文字(除其他外):
"\\'this"
'\\\'this'
say "\\'this"; # \'this
say '\\\'this'; # \'this
The answer is, of course答案当然是
s/[\\][']/\\\\'/g
This will match这将匹配
\'this
And substitute with this并用这个代替
\\'this
This was the only way I could get it to work.这是我让它工作的唯一方法。
Perl Perl
Too much "regexing" in your snippet.您的代码段中有太多“正则表达式”。 Try:尝试:
my $line = '\'this';
$line =~ s/'/\\\\\'/g;
printf('%s',$line);
print "\n";
# \\'this
or... if you want another mode:或者......如果你想要另一种模式:
my $line = '\'this';
$line =~ s/'/\\'/g;
printf('%s',$line);
print "\n";
# \'this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.