我有以下字符串: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
@布拉傑:他就是這麼做的。它不起作用,因爲他沒有任何只包含數字的括號。 –