简体   繁体   中英

perl extract/match last floating point number from string

Need to extract last floating point number from the string below and save into a variable.

F791775                (6010.822, 4396.812) (6013.341, 4405.921)   9.451  

Expected output: 9.451

Used the following regex

my $inj_spacing = $line =~ m {(\d+.\d+)}x;

but this extracts= 1

You get the number 1 as a result because your regex is in scalar context (because the left-hand side argument is a scalar). It is merely a true value, denoting that the regex matched.

What you want is to impose a list context, which can be done by adding parentheses:

my ($inj_spacing) = $line =~ m {(\d+\.\d+)}x;

(You also need to escape the period, as tools said)

Also, of course, this will match the first possible time, so you need to anchor it to the end:

my ($inj_spacing) = $line =~ m {(\d+\.\d+)\s*$}x;

I added \\s* to account for optional whitespace. This is not recommended if trailing whitespace indicates missing data in the last column (eg with csv data). But for an informal type of text matching, it will prevent false mismatches.

If your string always has that format, another option is to use split to get the last fp number:

use strict;
use warnings;

my $str = 'F791775                (6010.822, 4396.812) (6013.341, 4405.921)   9.451';
my $inj_spacing = ( split ' ', $str )[-1];
print $inj_spacing;

Output:

9.451

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM