返回多行中正则表达式匹配的行号

时间:2011-01-27 11:55:27

标签: regex perl

我正在尝试编写一个工具,它将找到跨越大文本文件中多行的空XML标记。例如。不匹配:

<tag>
ABC
</tag>

并匹配:

<tag>
</tag>

我在编写正则表达式以匹配多行中的空格时没有问题,但我需要找到这些匹配发生的行号(大约至少)。

我会将我的文本文件拆分成一个数组,但是匹配多个数组元素会非常棘手,因为可能有&gt; 2行标签/空格。

有什么想法吗?我的实现需要在Perl中。谢谢!

4 个答案:

答案 0 :(得分:4)

if ($string =~ $regex) {
    print "Match starting line number: ", 1 + substr($string,0,$-[0]) =~ y/\n//, "\n";
}

答案 1 :(得分:3)

在这种工作中,我宁愿使用xml解析器并输出结束空标记的行号,而不是尝试做一些繁琐的正则表达式工作。

答案 2 :(得分:0)

如果每行只有一个<tag>,则可以使用包含当前行号的特殊变量$.

#!/usr/bin/perl
use strict;
use warnings;
use 5.10.1;

my ($begin, $tag) = (0, 0, '');
while (my $line = <DATA>) {
  chomp $line;
  if ($line =~ m#<(tag).*?>#) {
    $tag = $1;
    $begin = $.;
    next;
  }
  if ($line =~ m#</($tag).*?>#) {
    if ($. - $begin < 2) {
      say "Empty tag '$tag' on lines $begin - $.";
    }
    $begin = 0;
    $tag = '';
  }
}

__DATA__
<tag>
ABC
</tag>

<tag>
</tag>

<强>输出:

Empty tag 'tag' on lines 5 - 6

答案 3 :(得分:0)

如果您需要强大的解决方案,请使用真正的XML解析器而不是天真的模式匹配。

如果你准备使用一种可能并不总能给出正确答案的脆弱方法, 然后看下面: - )

#!/usr/bin/perl
use warnings;
use strict;

my $xml =<<ENDXML;
<tag>
stuff
</tag>
<tag>


</tag>
<p>
paragraph
</p>
<tag> </tag>
<tag>
morestuff
</tag>
ENDXML

while ($xml =~ m#(<tag>\s*</tag>)#g) {
    my $tag = $1;

    # use substr() as an "lvalue" to find number of lines before </tag>
    my $prev_lines = substr($xml, 0, pos($xml)) =~ tr/\n// + 1;

    # adjust for newlines contained in the matched element itself
    my $tag_lines = $tag =~ tr/\n//;

    my $line = $prev_lines - $tag_lines;
    print "lines $line-$prev_lines\n$tag\n";
}