[英]Perl regular expression {} quantifier multiple matches
我正在嘗試分析一個文件,其中每行具有3個float(1,+ 1.0 -1.0是有效值),而代碼段中的正則表達式與float值匹配時,我不確定應該如何使用Perl量詞{ n}以匹配一行中的多個浮點數。
#!/usr/bin/perl
use strict;
use warnings;
open(my $fh, "<", "floatNumbers.txt") or die "Cannot open < floatNumbers.txt";
while(<$fh>)
{
if ($_=~m/([-+]?\d*[\.[0-9]*]?\s*)/)
{
print $1."\n";
}
}
代碼段,我嘗試在一行中匹配3個浮點數。 讀者可以幫助我正確使用{}量詞嗎?
if ($_=~m/([-+]?\d*[\.[0-9]*]?\s*){3}/)
您正在嘗試同時進行提取和驗證。 我會去:
sub is_float {
return $_[0] =~ /
^
[-+]?
(?: \d+(?:\.[0-9]*)? # 9, 9., 9.9
| \.[0-9]+ # .9
)
\z
/x;
}
while (<$fh>) {
my @fields = split;
if (@fields != 3 || grep { !is_float($_) } @fields) {
warn("Syntax error at line $.\n");
next;
}
print("@fields\n");
}
請注意,您的驗證不正確.
, [
和...0...0...
為數字。 我修好了
限定詞僅允許您指定要匹配正則表達式中某項的次數。
例如, /(ba){3}/
將與字符串中的ba
精確匹配3次:
bababanfnfd = bababa
但不是
爸爸=沒有比賽。
您還可以使用(摘自: http : //perldoc.perl.org/perlrequick.html ):
這是一種通用模式,我認為您正在談論的是:
# ^\s*(?:[-+]?(?=[^\s\d]*\d)\d*\.?\d*(?:\s+|$)){3}$
^ # BOL
\s* # optional whitespaces
(?: # Grouping start
[-+]? # optional -+
(?= [^\s\d]* \d ) # lookahead for \d
\d* \.? \d* # match this form (everything optional but guaranteed a \d)
(?: \s+ | $ ) # whitespaces or EOL
){3} # Grouping end, do 3 times
$ # EOL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.