繁体   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