2013-08-19 149 views
2

分组我有变量包含:No such file or directory at ./EMSautoInstall.pl line 50.正则表达式在Perl

我想创建变量包含No such file or directory,另一个包含at ./EMSautoInstall.pl line 50.

我正则表达式是:my ($eStmnt, $lineNO) = $! =~ /(.*[^a][^t])(.*)/;

当我打印两个变量中,第一个包含No such file or directory,但第二个是空的。

为什么会发生这种情况?

+1

对于一般的Perl正则表达式帮助,从'perldoc perlrequick'开始,当你已经征服它时,转到'perldoc perlre'。 – ThisSuitIsBlackNot

回答

7

真的$!变量中有那个字符串吗?因为通常,at line...部分由diewarn加上。我怀疑你只是有

$! = "No such file or directory"; 

而且您正则表达式匹配,因为它允许空字符串

/(.*[^a][^t])(.*)/ 

即第二次捕获也不匹配,第一次捕获可以是任何不以at结束的事情。

要确认,

print $!; 

应打印No such file or directory

+0

是的,你是对的:) –

+2

@M_E神秘解决了。 :)如果有疑问,'Data :: Dumper'模块是一个很好的调试工具:'print Dumper $ variable'。 – TLP

+1

+1,好侦探工作 – Zaid

1

您可以使用此:

((?:[^a]+|\Ba|a(?!t\b))+)(.*) 

的想法是匹配所有这不是一个“一”或“一个”不“在”

细节字的一部分:

(    # first capturing group 
    (?:   # open a non capturing group 
     [^a]+  # all that is not a "a" one or more times 
     |   # OR 
     \Ba  # a "a" not preceded by a word boundary 
     |   # OR 
     a(?!t\b) # "a" not followed by "t" and a word boundary 
    )+   # repeat the non capturing group 1 or more times 
)     # close the capturing group 
(.*)    # the second capturing group 

您可以改进这种模式,用原子组代替非捕获组,用占有量词替代量子。我们的目标是通过回溯位置的正则表达式引擎禁止的纪录,但结果保持不变:

((?>[^a]++|\Ba|a(?!t\b))++)(.*+) 
+0

你能解释一下吗?这是我第一次看到,因为我是Perl新手。 –

+0

非常感谢@Casimir et Hippolyte –

+0

我想问你我从哪里可以获得REGEX的这些知识 –

2

使用split这里先行断言使得比正则表达式捕获更多的意义:

my ($eStmnt, $lineNO) = split /(?=at)/, $!; 
+0

“?=”是什么意思? –