我想将以下字符串与下面的正则表达式进行比较。它似乎没有工作。有什么建议么?
要比较的字符串:“用户在 remoteexec.log 中搜索了“玩家”@ 02:21:31”
这是我的 perl 代码。
my $qu_re = q{(.?) searched (.?) for "(.?)" @ (\d+):(\d+):(\d+)};
你缺少一些量词,+
:
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 位数字。
这是一个例子:
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