[英]Perl Regular Expression - Dynamic Matches
假設我要匹配並捕獲5個由一個或多個空格分隔的整數-示例輸入:
1111 234 3333 456 7890
我可以這樣做:
my $input = '1111 234 3333 456 7890';
if($input =~ /^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)/)
{
#$1 = '1111', $2 = '234', $3 = '3333', $4= '456', $5 = '7890'
}
但是我想做這樣的事情來使正則表達式更簡單,而不是明確地將每個int重復5次:
my $input = '1111 234 3333 456 7890';
if($input =~ /^((\s*[0-9]+){5})/)
{
#$1 = '1111 234 3333 456 7890';
#$2 = ' 7890'
#all other capture variables are undefined
}
但是,捕獲似乎無法解決。
有沒有辦法我仍然可以訪問我的5個照片?
更好的是捕獲數量未知:
my $input = '1111 234 3333 456 7890';
if($input =~ /^((\s*[0-9]+)+)/)
{
#foreach capture 1..N do something...
}
my @numbers = $input =~ /\d+/g;
全局標志將返回列表上下文中的所有匹配項,這些匹配項將存儲在您的數組中。
如果知道分隔符是什么(在本例中為一個或多個空格),則不需要正則表達式即可捕獲所需的內容。 您可以使用split
。
use strict;
use warnings;
my $input = "1111 234 3333 456 7890";
my @ints=split /\s+/,$input;
print "$_\n" foreach(@ints);
產生輸出:
1111
234
3333
456
7890
線條的模式是否總是用空格分隔數字組? 如果是這樣,而不是正則表達式,為什么不基於空格拆分成數組
@outArray = split (/ +/,$input);
下面的代碼將捕獲前5個整數,如果這就是您想要的,則忽略其后的任何整數。 我可能不太清楚。
#!/usr/bin/perl
use strict;
use warnings;
my $in = '1111 234 3333 456 7890 12 13';
my @ints = (split ' ', $in)[0 .. 4];
print "@ints\n";
印刷品:
1111 234 3333 456 7890
克里斯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.