开发者

How to count the number of times a string (XML tag) occurs in a line?

Let's say my XML file has multiple <Timestamp> tags in a single line. I am reading the document line by line. How can I count how many of thes开发者_如何学Pythone tags are there in every line? I want something like:

foreach "<Timestamp>" in $line {
  print "FOund";
}

Any idea?


while ($line =~ /<Timestamp>/g) {
    print "Found\n";
}

should do the trick. The /g modifier is important there. See Using regular expressions in Perl in perlretut, it has a part on global matching.


It's XML, useXML::Twig:

my $twig = XML::Twig->new( twig_roots => { Timestamp => 1 });
$twig->parsefile( $xml_file_path );
my $timestamp_count = ( my @a = $twig->root->children( 'Timestamp' ));


The 'redo' control statement restarts execution of the current statement block. You can use it to write something like:

foreach $line (<>)
{
  $tag = $line =~ m/(<.*>)/;
  push @tags, $tag;
  if( $tag ) redo;
}

Be warned, I haven't run this.

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜