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

.+greedyの場合、可能な限り長い文字列に一致します。最短のものに一致させたい場合は、次を使用します.+?

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

または、空白に一致しない正規表現を使用します。

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

気が進まない/貪欲でない数量詞を使用して、最後ではなく最初の出現まで一致させます。「User」行にも「--User」が含まれている場合に備えて、どちらの場合もこれを行う必要があります。

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