我想将以下字符串与下面的正则表达式进行比较。它似乎没有工作。有什么建议吗?
要比较的字符串:“用户搜索remoteexec.log为”player“@ 02:21:31”
这是我的perl代码。
my $qu_re = q{(.?) searched (.?) for "(.?)" @ (\d+):(\d+):(\d+)};
答案 0 :(得分:3)
你缺少一些量词,+
:
my $qu_re = q{(.+?) searched (.+?) for "(.+?)" @ (\d+):(\d+):(\d+)};
^ ^ ^
否则,它们仅匹配0或1个字符。这应该适合你,但如果你问我,我宁愿使用更严格的限制:
my $qu_re = q{(\w+) searched (\w+\.log) for "(\w+)" @ (\d{2}):(\d{2}):(\d{2})};
尽管如此,我假设User
,player
和remoteexec
可以是字母数字并包含下划线。 {2}
附近\d
表示只有2位数字。
答案 1 :(得分:1)
这是一个例子:
use strict;
use warnings;
my $str = qq{User searched remoteexec.log for "player" @ 02:21:31};
my $qu_re = qr{(.+) searched (.+) for "([^"]+)" @ (\d+):(\d+):(\d+)};
if( $str =~ m/$qu_re/ ) {
print "user: ", $1, "\n";
print "what: ", $2, "\n";
print "player: ", $3, "\n";
print "when: ", "$4:$5:$6" , "\n";
}
打印:
user: User
what: remoteexec.log
player: player
when: 02:21:31