![](/img/trans.png)
[英]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.