2016-01-04 109 views
1

我有以下字符串:Perl的正则表达式提取的字符串与数字括号

my $string = "Ethernet FlexNIC (NIC 1) LOM1:1-a FC:15:B4:13:6A:A8"; 

我想提取是在(1)中的另一变量括号中的数字。 下面的语句不起作用:

my ($NAdapter) = $string =~ /\((\d+)\)/; 

什么是正确的语法?

+0

像'\((\ d +)\)'这样的转义括号,并得到第一个匹配的组。 – Braj

+0

@布拉杰:他就是这么做的。它不起作用,因为他没有任何只包含数字的括号。 –

回答

1
\d+(?=[^(]*\)) 

您可以使用this.See demo.Yours将无法正常工作,内部()有除了\d+更多的数据。

https://regex101.com/r/fM9lY3/57

+0

为什么downvoted ??????????? – vks

1

你可以尝试像

my ($NAdapter) = $string =~ /\(.*(\d+).*\)/; 

之后,$NAdapter应该包括你要的号码。

+0

这不会在'(NIC 1233 232)' – vks

+0

@vks的情况下工作是的,我的解决方案只比海报需要的更通用一点,而不是最通用的解决方案。 –

0
my $string = "Ethernet FlexNIC (NIC 1) LOM1:1-a FC:15:B4:13:6A:A8"; 

我想提取方括号中(1)在另一个 可变

您正则表达式的数量(有一些空间为清楚起见):

/ \((\d+) \) /x; 

说匹配:

  1. 字母开括号,紧接着...
  2. 一个数字,一次或多次(在组1中捕获),紧接着...
  3. 字面右括号。

然而,要匹配的字符串:

(NIC 1) 

的形式为:

  1. 一个文字左括号,紧接着...
  2. 一些大写字母 停止一切!不匹配!

作为替代,你的子:

(NIC 1) 

可以描述为:

  1. 一些数字,紧接着...
  2. 字面上的右括号。

这里的正则表达式:

use strict; 
use warnings; 
use 5.020; 

my $string = "Ethernet FlexNIC (NIC 1234) LOM1:1-a FC:15:B4:13:6A:A8"; 

my ($match) = $string =~/
    (\d+) #Match any digit, one or more times, captured in group 1, followed by... 

    \)  #a literal closing parenthesis. 
      #Parentheses have a special meaning in a regex--they create a capture 
      #group--so if you want to match a parenthesis in your string, you 
      #have to escape the parenthesis in your regex with a backslash. 

/xms; #Standard flags that some people apply to every regex. 

say $match; 

--output:-- 
1234 

你的子串的另一种描述:

(NIC 1) 

可能是:

  1. 一个文字左括号,紧接着...
  2. 部分否n位,紧接着...
  3. 一些数字,紧接着是......
  4. 一个字面右括号。

这里的正则表达式:

use strict; 
use warnings; 
use 5.020; 

my $string = "Ethernet FlexNIC (ABC NIC789) LOM1:1-a FC:15:B4:13:6A:A8"; 

my ($match) = $string =~/

    \(  #Match a literal opening parethesis, followed by... 
    \D+  #a non-digit, one or more times, followed by... 
    (\d+) #a digit, one or more times, captured in group 1, followed by... 
    \)  #a literal closing parentheses. 

/xms; #Standard flags that some people apply to every regex. 

say $match; 

--output:-- 
789 

一些线路如果有可能的空间,而不是其他,如:

spaces 
     || 
     VV 
(NIC 1 ) 
(NIC 2) 

您可以将\s*(任何空白,零或更多次)在正则表达式中的适当位置,例如:

my ($match) = $string =~/
      #Parentheses have special meaning in a regex--they create a capture 
      #group--so if you want to match a parenthesis in your string, you 
      #have to escape the parenthesis in your regex with a backslash. 
    \(  #Match a literal opening parethesis, followed by... 

    \D+  #a non-digit, one or more times, followed by... 
    (\d+) #a digit, one or more times, captured in group 1, followed by... 
    \s*  #any whitespace, zero or more times, followed by... 
    \)  #a literal closing parentheses. 

/xms; #Standard flags that some people apply to every regex.