我是一个regex新手,我正在尝试使用regex从文本文件中返回日期列表。日期采用mm/dd/yy格式,因此对于年份来说,例如“1955”,它将是“55”。我正在尝试返回从‘50’到'99‘的所有条目。
我认为我遇到的问题是,一旦我的正则表达式在一行上找到匹配项,它就会停在那里,跳到下一行,而不检查该行的其余部分。例如,在文本文件中,日期12/12/12、10/10/57、10/09/66都在一行上,而它只返回10/10/57。
到目前为止,这是我的代码。有什么提示或建议吗?谢谢
open INPUT, "< dates.txt" or die "Can't open input file: $!";
while (my $line = <INPUT>){
if ($line =~ /(\d\d)\/(\d\d)\/([5-9][0-9])/g){
print "$&\n" ;
}
}发布于 2016-04-06 16:22:35
关于您的代码的几个要点
use strict和use warnings 'all'在你所有的Perl程序的顶端$1代替此程序将按您的要求执行
use strict;
use warnings 'all';
open my $fh, '<', 'dates.txt' or die "Can't open input file: $!";
while ( <$fh> ) {
print $1, "\n" while m{(\d\d/\d\d/[5-9][0-9])}g
}输出
10/10/57
10/09/66发布于 2016-04-06 12:23:01
你只需要把'if‘改成'while’,正则表达式就会回到它停止的地方;
open INPUT, "< a.dat" or die "Can't open input file: $!";
while (my $line = <INPUT>){
while ($line =~ /(\d\d)\/(\d\d)\/([5-9][0-9])/g){
print "$&\n" ;
}
}
# Output given line above
# 10/10/57
# 10/09/66您还可以将整个日期捕获到一个捕获变量中,并使用不同的正则表达式分隔符来保存对斜杠的转义:
while ($line =~ m|(\d\d/\d\d/[5-9]\d)|g) {
print "$1\n" ;
}...but这可能是品味的问题。
发布于 2016-04-06 12:28:51
您打印的是$&,每当遇到任何新的匹配项时都会更新。
但在这种情况下,您需要存储所有以前的匹配和更新后的匹配,因此您可以使用array来存储所有匹配。
while(<$fh>) {
@dates = $_ =~ /(\d\d)\/(\d\d)\/([5-9][0-9])/g;
print "@dates\n" if(@dates);
}https://stackoverflow.com/questions/36441290
复制相似问题