Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Regex issues

Tags:

regex

perl

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;
        }
    }
}
like image 874
genx1mx6 Avatar asked Dec 04 '25 06:12

genx1mx6


1 Answers

.+ 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+)/;
like image 180
Barmar Avatar answered Dec 11 '25 22:12

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!