因此,我试图获得perl中正则表达式的所有匹配,但是输出中混合了奇怪的值?这是我的perl代码:
#!/usr/bin/env perl
use strict;
use warnings;
my $filename="test.txt";
my $data;
open($data,$filename) or die "couldn't open the file";
while(<$data>)
{
chomp($_);
my @count = ($_ =~ /(((\d){1,4}(\s|\-|\.|\/)){1,3}(\d){2,4})/g);
print @count;
print "\n";
}我的文本文件的内容如下:
content 10-12-2015
content 10 12 2015
content 10-12-2015
content 10/12/2015
content 10.12.2015
content 10.12.15
content 10.12.1412
content 1992.12.30
content 22/04/96
content 1996-04-22
content 22.04.96
content 10.12.1412
content 1992.12.30
content 22/04/96
content 04/22/96真正奇怪的输出是匹配的正则表达式和其他值吗?在数组中。
10-12-201512-2-5
10 12 201512 2 5
10-12-201512-2-5
10/12/201512/2/5
10.12.201512.2.5
10.12.1512.2.5
10.12.141212.2.2
1992.12.3012.2.0
22/04/9604/4/6
1996-04-2204-4-2
22.04.9604.4.6
10.12.141212.2.2
1992.12.3012.2.0
22/04/9604/4/6
04/22/9622/2/6正常产出的一个例子是: 10-12-2015,但这个数值从12-2-5中得到了什么?问题是,在我的另一个文本文件中,一行中有多个日期,这意味着我不能只从数组中获得第一个匹配。
请帮帮忙。。。。好了!我对Perl很陌生,这让我很难受!
发布于 2016-03-24 21:43:09
这个值是从12到2到5的哪里来的?
由于您使用的是嵌套捕获组,所以它捕获了各个部分。
从10-12-2015获取12- 2 - 5,这反映在完成10-12-2015捕获之后的结果中。每个例子都是一样的。
要只提取日期,可以使用此正则表达式。
Regex: (?:\d{2}|\d{4})[-\/\.\s]\d{2}[-\/\.\s](?:\d{4}|\d{2})
此正则表达式不使用捕获组。
发布于 2016-03-25 00:16:36
可能太晚了,但是使用noobs regex捕获组您的代码可能如下所示
#!/usr/bin/env perl
use strict;
use warnings;
my $filename="file.txt";
my $data;
open($data,$filename) or die "couldn't open the file";
while (my $line = <$data>){
chomp($line);
my (@count) = $line =~ /((?:\d{2}|\d{4})[-\/\.\s]\d{2}[-\/\.\s](?:\d{4}|\d{2}))/g;
print join(" : ", @count);
print "\n";
}输出
10-12-2015
10 12 2015 : 10.12.2015 : 11-23-2014
10-12-2015
10/12/2015
10.12.2015
10.12.15
10.12.1412 : 10.12.1412
1992.12.30
22/04/96
1996-04-22
22.04.96
10.12.1412
1992.12.30 : 10.12.2015
22/04/96
04/22/96发布于 2016-03-24 21:52:28
当您对这些值不感兴趣时,不应该在regexp中使用如此多的分组。
每个开头的(都会在结果列表中提供一个值。
您可能会使用以下轻微的resexp来最小化分组,并且每次匹配只需要处理2个值:
$_ =~ /((\d{1,4}[\s.\\-]){1,3}\d{2,4})/ghttps://stackoverflow.com/questions/36210341
复制相似问题