views:

112

answers:

6

I'm trying to capture the last digits in this line in a regex group:

The input:

9 Power_On_Hours          0x0032   099   099   000    Old_age   Always       -       54654

My pattern:

/Power_On_Hours.+Always\s.+([0-9]{1,5})/

I just can't seem to get it to capture "54654", it's returning undef :(

+1  A: 
#!/usr/bin/perl

use strict; use warnings;

my $s = q{9 Power_On_Hours          0x0032   099   099   000    Old_age   Always       -       54654};

my ($interesting) = $s =~ /([0-9]{1,5})\z/;
print "$interesting\n";
Sinan Ünür
+7  A: 

Actually, that capture group should grab '4', not undef. Your final .+ will eat up everything until the last digit and then capture that to $1. This revision captures all the digits to $1:

/Power_On_Hours.+Always\s.+?(\d{1,5})/

The ? makes the .+ non-greedy, so it will match characters up to when the digits (\d) start to match.

friedo
Friedo, You are a god my friend. That's it!
JPerkSter
+4  A: 

As friedo pointed out, the trouble is that your last .+ is greedy (the default behaviour) and you can fix it by changing it to .+?.

But I would probably use the $ to match end of line, so:

/Power_On_Hours.+Always.+?(\d+)$/
Hans W
+1  A: 

if your digits are always last ,

$string= q(9 Power_On_Hours          0x0032   099   099   000    Old_age   Always       -       54654);
@s = split /\s+/,$string;
print $s[-1]."\n";

and if last digits can be any length

/.+Power.+Always.+[^\d](\d+)$/;
ghostdog74
A: 

The last group of digits in the line, right?

my ($digits) = $input =~ /(\d+)$/;

The $ sign anchors the group of one or more digits, (\d+), to the end of the string.

Zaid
+1  A: 

Dear Friend,

You can use the following code also,

use strict;
use warnings;

my $string= q(9 Power_On_Hours          0x0032   099   099   000    Old_age   Always       -       54654);
my @array = split /\s+/,$string;

print "$array[$#array]\n";
muruga