我正在从事Perl任务。要求之一是匹配所有整数和浮点数,但注释或字符串(双引号或单引号)除外。
这是我的假设:
这是我发现的正则表达式。
([-+]?([0-9]+(\.[0-9]+)?|\.[0-9]+))
这是我的代码块,在排除注释和字符串中的数字时遇到了麻烦,因此我首先删除了所有注释和字符串。我也将行分割成单词,我相信这应该更容易。但是我也认为这没有必要。
while (<$IN_FILE>) {
s/^(#[^!]+$)//; # remove whole line comments
s{(^[^#]+?)(#[^/]+$)}{$1}; # remove inline comments
s/('.*?'|".*?")//g; # remove all single line strings
push @words, split; # split line into words
}
foreach my $item (<@words>) {
push @numbers, $1 if $item =~ /([-+]?([0-9]+(\.[0-9]+)?|\.[0-9]+))/;
}
它工作正常,但无法匹配0
in中的数组索引ARGV[0]
。
因此,我需要一些帮助来改进我的代码,如果我不必先删除注释,字符串,也不需要将行拆分成单词,并且当然匹配注释和字符串中没有的所有数字,那将是很好的选择。
简单输入
# Comment 1
my $time = <STDIN>;
chomp $time;
#now write input to STDOUT
print $time . "\n";
my $pi = 3.1415926;
my $test = -3.22;
my $t = +0.01;
my $range = (8..11);
if $ARGV[0];
sub sample2 {
print "true or false";
return 3 + 4 eq "7"; # true or false
}
下面是从我的代码输出它错过了0
中ARGV[0]
和11
的(8..11)
。如果错过更多,我不会感到惊讶。
[Numbers]
3.1415926
-3.22
+0.01
8
2
3
4
主要问题在这里:
foreach my $item (<@words>) {
您想遍历@words,所以<>
不需要。它们变成glob
您要迭代的列表所进行的更改。只需插入
warn "\t$item\n"
进入最后一个循环以查看正在处理的内容。
即使解决了这个问题,(8..11)
也将被标记为一个“单词”。您没有任何匹配项/g
,因此您不能从一个项目中获得多个数字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句