正则表达式是不工作
问题描述:
my $pat = '^x.*d$';
my $dir = '/etc/inet.d';
if ($dir =~ /$pat/xmsg) {
print "found ";
}
如何使它sucess正则表达式是不工作
答
您可以使用YAPE::Regex::Explain,帮助您了解正则表达式:
use strict;
use warnings;
use YAPE::Regex::Explain;
my $re = qr/^x.*d$/xms;
print YAPE::Regex::Explain->new($re)->explain();
__END__
The regular expression:
(?msx-i:^x.*d$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?msx-i: group, but do not capture (with^and $
matching start and end of line) (with .
matching \n) (disregarding whitespace and
comments) (case-sensitive):
----------------------------------------------------------------------
^ the beginning of a "line"
----------------------------------------------------------------------
x 'x'
----------------------------------------------------------------------
.* any character (0 or more times (matching
the most amount possible))
----------------------------------------------------------------------
d 'd'
----------------------------------------------------------------------
$ before an optional \n, and the end of a
"line"
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
而且,你不需要在这种情况下,g
修改。该文档有大量的有关正则表达式的信息:perlre
答
你的模式是寻找开始X(^x
)字符串和d(d$
)结束。您尝试的路径不匹配,因为它不以x开头。
答
有一个“X”太多:
my $pat = '^.*d$';
my $dir = '/etc/inet.d';
if ($dir =~ /$pat/xmsg) {
print "found ";
}
答
我的猜测是,您正试图列出名称与正则表达式匹配的所有文件(/etc/init.d
)。
Perl不够聪明,当你命名一个字符串变量$dir
时,给它指定一个现有目录的完整路径名,并对它进行模式匹配,你不打算匹配路径名, 但针对该目录中的文件名。
解决这个问题的一些方法:
perldoc -f glob
perldoc -f readdir
perldoc File::Find
你可能只是想用这样的:
if (glob('/etc/init.d/x*'))
{
warn "found\n";
}
什么是你真正想匹配?如果我们不知道*你想匹配**,那么我们就不能“成功”。正则表达式需求细节。 – Stephen 2010-08-18 15:38:11
也许如果你解释了你认为你的正则表达式模式应该被发现? – 2010-08-18 15:38:23
在'$ dir'开始处放置一个x或从'$ pat'中的^之后移除'x'。 – Axeman 2010-08-18 16:56:43