English 中文(简体)
regex: 从字符串 {} 示例中提取 3 个具体数字
原标题:regex: extract 3 specific numbers from a string | example
  • 时间:2012-05-24 18:49:47
  •  标签:
  • regex

给定以下两行字符串,例如 :

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

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

[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

请你帮我一下好吗?

感激多多多多多 感谢

最佳回答

要获得第一个 ( , 我们可以使用 . * ((d+) ) 之后的第一个号码。 然后, 要在 / 之后获得第一个号码, 我们可以使用 /(d+)) () 之后的第一个号码。 然后, 在“ link” 之后获得第一个号码 : [lL]ink (d+) 之后, 我们把这些编号放在一起来获取。

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

这三个数字将分为三个组

问题回答

这个在这里工作

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

给您输入,它会还回来

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

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
";
$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
" if m!((d+)/(d+)).*?(?:L|l)inks+(d+)!;
}

产出 :

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




相关问题
Uncommon regular expressions [closed]

Recently I discovered two amazing regular expression features: ?: and ?!. I was curious of other neat regex features. So maybe you would like to share some tricky regular expressions.

regex to trap img tag, both versions

I need to remove image tags from text, so both versions of the tag: <img src="" ... ></img> <img src="" ... />

C++, Boost regex, replace value function of matched value?

Specifically, I have an array of strings called val, and want to replace all instances of "%{n}%" in the input with val[n]. More generally, I want the replace value to be a function of the match ...

PowerShell -match operator and multiple groups

I have the following log entry that I am processing in PowerShell I m trying to extract all the activity names and durations using the -match operator but I am only getting one match group back. I m ...

Is it possible to negate a regular expression search?

I m building a lexical analysis engine in c#. For the most part it is done and works quite well. One of the features of my lexer is that it allows any user to input their own regular expressions. This ...

regex for four-digit numbers (or "default")

I need a regex for four-digit numbers separated by comma ("default" can also be a value). Examples: 6755 3452,8767,9865,8766,3454 7678,9876 1234,9867,6876,9865 default Note: "default" ...

热门标签