繁体   English   中英

带有 \\g 的字符串的 Perl 正则表达式抛出错误

[英]Perl Regular expression for string with \g throws error

$warning_line="C:\PGMFile\VERSION\ghunt\ol.txt";
$newWarning="C:\PGMFile\VERSION\ghunt\ol.txt";
if ($warning_line =~  $newWarning)
{           
    some logic
}

抛出错误

Reference to invalid group 0 in regex; marked by <-- HERE in m/"C:\PGMFile\VERSION\g <-- HERE hunt\ol.txt", line 3 

反斜杠必须在双引号中加倍并在正则表达式中加倍,因此以下更改应该修复。

# qq for double quotes
$newWarning = qq(C:\\\\PGMFile\\\\VERSION\\\\ghunt\\\\ol.txt)

否则使用 quotemeta 或\\Q ... \\E

# q for single quotes
$newWarning = quotemeta( q(C:\PGMFile\VERSION\ghunt\ol.txt) )

注意:即使在单引号内反斜杠也是一个转义字符,因为它可以转义最后的引号定界符,所以双反斜杠代表单反斜杠。

要么

if ($warning_line =~  /\Q$newWarning\E/)

首先,这些和你想的不一样

$warning_line="C:\PGMFile\VERSION\ghunt\ol.txt";
$newWarning="C:\PGMFile\VERSION\ghunt\ol.txt";

\\在双引号字符串中具有特殊含义。 结果,您在那里拥有的甚至无法编译。

$ perl -M5.010 -we'
   $warning_line = "C:\PGMFile\VERSION\ghunt\ol.txt";
   say $warning_line;
'
Unrecognized escape \P passed through at -e line 2.
Unrecognized escape \V passed through at -e line 2.
Unrecognized escape \g passed through at -e line 2.
Missing braces on \o{} at -e line 2, within string
Execution of -e aborted due to compilation errors.

你想要什么:

my $warning_line = "C:\\PGMFile\\VERSION\\ghunt\\ol.txt";
my $newWarning   = "C:\\PGMFile\\VERSION\\ghunt\\ol.txt";

"C:\\\\PGMFile\\\\VERSION\\\\ghunt\\\\ol.txt"产生字符串C:\\PGMFile\\VERSION\\ghunt\\ol.txt


其次,既然我们在变量中得到了字符串C:\\PGMFile\\VERSION\\ghunt\\ol.txt ,那么还有第二个问题。 \\在正则表达式模式中很特殊。 您可以使用quotemeta\\Q..\\E来解决这个问题。

# If $warning_line contains $newWarning
if ($warning_line =~ /\Q$newWarning\E/) {   # Trailing \E can be omitted.
   ...
}
# If $warning_line is equal to $newWarning
if ($warning_line =~ /^\Q$newWarning\E\z/) {
   ...
}
# If $warning_line is equal to $newWarning
if ($warning_line eq $newWarning) {
   ...
}

暂无
暂无

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

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