genx1mx6
genx1mx6

Reputation: 453

Perl Regex issues

why isn't this perl REGEX working? i'm grabbing the date and username (date works fine), but it will grab all the usernames then when it hits bob.thomas and grabs the entire line

Code:

m/^(.+)\s-\sUser\s(.+)\s/;
print "$2------\n";

Sample Data:

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. 

for the user that asked for the full code

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;
        }
    }
}

Upvotes: 2

Views: 193

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191809

Use the reluctant/ungreedy quantifier to match up until the first occurrence rather than the last. You should do this in both cases just in case the "User" line also has " - User "

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

Upvotes: 3

Barmar
Barmar

Reputation: 782498

.+ is greedy, it matches the longest possible string. If you want it to match the shortest, use .+?:

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

Or use a regexp that doesn't match whitespace:

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

Upvotes: 8

Related Questions