正则表达式:从字符串中提取3个特定数字例

时间:2012-05-24 18:49:47

标签: regex

给出以下2行字符串,例如:

May 22 00:46:38.340  prod-lab03c-rd1 fpc4 XETH(4/2): %PFE-6: Link 0 XFP: Low Rx power warning set
[May 24 11:24:28.299 LOG: Notice] MIC(0/1) link 1 SFP receive power low  warning set

我想在3个变量中存储以下数字:

[1] the 1st number after the "(", it could be 1 or more digits
[2] the 1st number after the "/", it could be 1 or more digits
[3] the first number after the "(L|l)ink" word, it could be 1 or more digits
你能帮我解决这个问题吗?

非常感谢

3 个答案:

答案 0 :(得分:3)

要获取第一个(之后的第一个数字,我们可以使用.*\((\d+)。然后,为了获得/之后的第一个数字,我们可以使用/(\d+)\)。然后在“链接”之后得到第一个数字:[lL]ink (\d+)。我们把这些放在一起

^.*\((\d+)/(\d+)\).*[lL]ink (\d+)

三个数字将分为三组

答案 1 :(得分:1)

这可以在这里工作

\((.*?)/(.*?)\).*?[Ll]ink (\d+)

给你的输入它会回馈

group 1  group 2 group 3
4        2       0
0        1       1

答案 2 :(得分:0)

Perl中完整的测试示例:

#!/usr/bin/env perl

use strict;
use warnings;

my @a;

$a[0] = "May 22 00:46:38.340  prod-lab03c-rd1 fpc4 XETH(4/2): %PFE-6: Link 0 XFP: Low Rx power warning set\n";
$a[1] = "[May 24 11:24:28.299 LOG: Notice] MIC(0/1) link 1 SFP receive power low  warning set";

foreach (@a) {
    print "\$1=$1|\$2=$2|\$3=$3\n" if m!\((\d+)/(\d+)\).*?(?:L|l)ink\s+(\d+)!;
}

输出:

$1=4|$2=2|$3=0
$1=0|$2=1|$3=1