我有以下字符串:
my $string = "Ethernet FlexNIC (NIC 1) LOM1:1-a FC:15:B4:13:6A:A8";
我想在另一个变量中提取括号(1)中的数字。 以下声明不起作用:
my ($NAdapter) = $string =~ /\((\d+)\)/;
正确的语法是什么?
答案 0 :(得分:2)
答案 1 :(得分:1)
您可以尝试类似
的内容my ($NAdapter) = $string =~ /\(.*(\d+).*\)/;
之后,$NAdapter
应包含您想要的号码。
答案 2 :(得分:0)
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.