简体   繁体   English

Perl,模式匹配和元字符

[英]Perl, pattern matching and metacharacters

I am trying to match two things which both are full of metacharacters that needs to be used as 'Literal' in my match pattern. 我正在尝试匹配两个都充满了元字符的东西,这些东西需要在我的匹配模式中用作“文字”。 \\Q is suppose to quote all metacharacter in a string until \\E ...but it doesn't work. \\Q假定在字符串中用引号引起所有元字符,直到\\E ...但是它不起作用。

Whats up with that? 那是怎么回事?

this is the line that gives me trouble : if (/\\Q$prev\\E/ !~ /\\Q$ww[0]\\E/) { 这是给我带来麻烦的那一行: if (/\\Q$prev\\E/ !~ /\\Q$ww[0]\\E/) {

Absent the use of =~ or !~ , 如果不使用=~!~

/.../

is short for 是短的

$_ =~ m/.../

so 所以

/\Q$prev\E/ !~ /\Q$ww[0]\E/

is short for 是短的

($_ =~ /\Q$prev\E/) !~ /\Q$ww[0]\E/

which is equivalent to one of the following depending on whether the left regex match succeeds or not: 根据左边的正则表达式匹配是否成功,它等于以下之一:

"" !~ /\Q$ww[0]\E/
"1" !~ /\Q$ww[0]\E/

You simply want: 您只想要:

$prev !~ /\Q$ww[0]\E/   # $ww[0] doesn't contains $prev

If you actually want 如果你真的想要

$prev !~ /^\Q$ww[0]\E\z/   # $ww[0] isn't equal to $prev

then you can simplify that to 然后您可以简化为

$prev ne $ww[0]   # $ww[0] isn't equal to $prev

By the way, always use use strict; use warnings; 顺便说一句,请始终use strict; use warnings; use strict; use warnings; . It may have identified a problem here (but not necessarily, depending on the value of $_ ). 它可能已经在这里确定了一个问题(但不一定,取决于$_的值)。

It looks like you want to compare a string in $prev to one in $ww[0] . 看来您想将$prev的字符串与$ww[0]的字符串进行比较。 If this is the case, a regex match should look like this: 如果是这种情况,则正则表达式匹配应如下所示:

$result = $prev !~ /\Q$ww[0]\E/

$result will return 1 if $prev is not the same as whatever is in www[0] , ignoring metacharacters. 如果$prevwww[0] ,则$result将返回1 ,忽略元字符。

However if that is all you wanted to do, you might as well use ne : 但是,如果您只想这样做,则不妨使用ne

if ($prev ne $ww[0]){ 
   #do this if $prev and $ww[0] are not the same
} 

Also, as @toolic has mentioned, add the following line to the top of your script: 另外,正如@toolic所提到的,将以下行添加到脚本顶部:

use warnings;

This will give you some feedback on possible problems in your scripts. 这将给您一些有关脚本中可能出现的问题的反馈。

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

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