2016-01-04 110 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.