2

为什么这个 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;
        }
    }
}
4

2 回答 2

8

.+贪婪的,它匹配最长的可能字符串。如果您希望它匹配最短,请使用.+?

/^(.+)\s-\sUser\s(.+?)\s/;

或者使用与空格不匹配的正则表达式:

/^(.+)\s-\sUser\s(\S+)/;
于 2013-02-16T21:44:14.300 回答
3

使用不情愿/不贪婪的量词匹配直到第一次出现而不是最后一次出现。你应该在这两种情况下都这样做,以防“用户”行也有“-用户”

m/^(.+?)\s-\sUser\s(.+?)\s/;
于 2013-02-16T21:46:04.653 回答