从perl中的字符串中提取十进制数

时间:2011-12-14 14:37:16

标签: string perl

从下面一行我需要在“Info”之后提取十进制数,即1.1.3:

Imagetest Test ID 10159 Type MANUAL Designer xyzz (u887) Product WW EEE Date 3/4/2010 Execution Status No Run Status Approved VC Info 1.1.3, CheckedIn 

如何使用Perl正则表达式执行此操作?

4 个答案:

答案 0 :(得分:1)

my $string = 'Imagetest Test ID 1.2.3 10159 Type MANUAL Designer xyzz (u887) Product WW EEE Date 3/4/2010 Execution Status No Run Status Approved VC Info 1.1.3, CheckedIn';
my ($number) = $string =~ m{
    (?<= Info \s )  # Look behind to check if we found: 'Info '
    (
        \d+  # 1
        \.   # .
        \d+  # 1
        \.   # .
        \d+  # 3
    )
}x;

上述正则表达式可简化为以下内容:

m{
    (?<= Info \s )  # Look behind to check if we found: 'Info '
    (
        (?:
            \d+
            \.
        ){2} # 1.1.
        \d+  # 3
    )
}x;

答案 1 :(得分:1)

首先,1.1.3不是十进制数。它是由句点分隔的ASCII数字序列。只需查找Info后跟这样一系列字符。

#!/usr/bin/env perl

use strict; use warnings;

my $s = q{Imagetest Test ID 10159 Type MANUAL Designer xyzz (u887) Product
WW EEE Date 3/4/2010 Execution Status No Run Status Approved VC Info 1.1.3,
CheckedIn};

my $re = qr{
    Info
    \s+
    (
        [0-9]+
        (?:
            [.]
            [0-9]+
        )* # use + if a sequence without periods is not possible
    )
}x;


if (my ($info) = ($s =~ $re)) {
    print "$info\n";
}

答案 2 :(得分:0)

尝试一次:

^(\d+\.)?(\d+\.)?(\*|\d+)$

答案 3 :(得分:0)

m{VC Info\s+([\d\.]+)} and print $1