[英]Perl regex to extract groups of digits from string of dot-separated integers
[英]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+)\)/;
什么是正确的语法?
你可以试试像
my ($NAdapter) = $string =~ /\(.*(\d+).*\)/;
之后, $NAdapter
应该包含您想要的数字。
my $string = "Ethernet FlexNIC (NIC 1) LOM1:1-a FC:15:B4:13:6A:A8";
我想在另一个变量中提取括号(1)中的数字
你的正则表达式(为了清晰起见,有一些空格):
/ \( (\d+) \) /x;
说匹配:
然而,您要匹配的子字符串:
(NIC 1)
具有以下形式:
作为替代方案,您的子字符串:
(NIC 1)
可以描述为:
这是正则表达式:
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)
可能:
这是正则表达式:
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.