我有以下字符串:Perl的正则表达式提取的字符串与数字括号
my $string = "Ethernet FlexNIC (NIC 1) LOM1:1-a FC:15:B4:13:6A:A8";
我想提取是在(1)中的另一变量括号中的数字。 下面的语句不起作用:
my ($NAdapter) = $string =~ /\((\d+)\)/;
什么是正确的语法?
我有以下字符串:Perl的正则表达式提取的字符串与数字括号
my $string = "Ethernet FlexNIC (NIC 1) LOM1:1-a FC:15:B4:13:6A:A8";
我想提取是在(1)中的另一变量括号中的数字。 下面的语句不起作用:
my ($NAdapter) = $string =~ /\((\d+)\)/;
什么是正确的语法?
为什么downvoted ??????????? – vks
你可以尝试像
my ($NAdapter) = $string =~ /\(.*(\d+).*\)/;
之后,$NAdapter
应该包括你要的号码。
这不会在'(NIC 1233 232)' – vks
@vks的情况下工作是的,我的解决方案只比海报需要的更通用一点,而不是最通用的解决方案。 –
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.
像'\((\ d +)\)'这样的转义括号,并得到第一个匹配的组。 – Braj
@布拉杰:他就是这么做的。它不起作用,因为他没有任何只包含数字的括号。 –