![](/img/trans.png)
[英]regex to match multiple times per line and across lines, but not after comment
[英]Returning line numbers of a regex match across multiple lines
我正在尝试编写一个工具,该工具将查找在大型文本文件中跨多行的空XML标记。 例如不匹配:
<tag>
ABC
</tag>
并匹配:
<tag>
</tag>
我编写正则表达式以跨多行匹配空白没有问题,但是我需要找到发生这些匹配的行号(至少大约)。
我会将文本文件拆分成一个数组,但是要匹配多个数组元素将非常棘手,因为标签/空白可能超过2行。
有任何想法吗? 我的实现需要在Perl中进行。 谢谢!
if ($string =~ $regex) {
print "Match starting line number: ", 1 + substr($string,0,$-[0]) =~ y/\n//, "\n";
}
在这种工作中,我宁愿使用xml解析器并输出结束的空标记的行号,而不是尝试进行一些繁琐的正则表达式工作。
如果每行只有一个<tag>
,则可以使用specail变量$.
包含当前行号。
#!/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
如果需要可靠的解决方案,请使用真实的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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.