簡體   English   中英

Perl正則表達式用括號從字符串中提取數字

[英]Perl regex to extract digits from string with parenthesis

我有以下字符串:

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

我想在另一個變量中提取括號(1)中的數字。 以下聲明不起作用:

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

什么是正確的語法?

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

你可以使用它。參見demo.Yours不能作為inside ()除了\\d+之外還有更多的數據。

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

你可以試試像

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

之后, $NAdapter應該包含您想要的數字。

 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. 一些非數字,緊接着......
  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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM