为什么这个perl REGEX不工作?我抓住了日期和用户名(日期工作正常),但它会抓住所有用户名,然后当它击中bob.thomas并抓住整行
代码:
m/^(.+)\s-\sUser\s(.+)\s/;
print "$2------\n";
示例数据:
Feb 17, 2013 12:18:02 AM - User plasma has logged on to client from host
Feb 17, 2013 12:13:00 AM - User technician has logged on to client from host
Feb 17, 2013 12:09:53 AM - User john.doe has logged on to client from host
Feb 17, 2013 12:07:28 AM - User terry has logged on to client from host
Feb 17, 2013 12:04:10 AM - User bob.thomas has been logged off from host because its web server session timed out. This means the web server has not received a request from the client in 3 minute(s). Possible causes: the client process was killed, the client process is hung, or a network problem is preventing access to the web server.
表示要求提供完整代码的用户
open (FILE, "log") or die print "couldn't open file";
$record=0;
$first=1;
while (<FILE>)
{
if(m/(.+)\sto now/ && $first==1) # find the area to start recording
{
$record=1;
$first=0;
}
if($record==1)
{
m/^(.+)\s-\sUser\s(.+)\s/;
<STDIN>;
print "$2------\n";
if(!exists $user{$2})
{
$users{$2}=$1;
}
}
}
答案 0 :(得分:7)
.+
greedy ,它匹配最长的字符串。如果您希望它与最短匹配,请使用.+?
:
/^(.+)\s-\sUser\s(.+?)\s/;
或者使用与空格不匹配的正则表达式:
/^(.+)\s-\sUser\s(\S+)/;
答案 1 :(得分:2)
使用不情愿/不同意量词来匹配直到第一次出现而不是最后一次出现。你应该在两种情况下都这样做,以防“用户”行也有“ - 用户”
m/^(.+?)\s-\sUser\s(.+?)\s/;