如何在Perl中的两个字符之间从XML中获取文本

时间:2013-07-10 14:03:55

标签: xml perl

我有一个大文件,我想解析并从中获取选择的文本片段。以下是文件中的实际示例:

en-US   AcceptedText pt="dial:def"Tag u="contact"Mom/Tag/AcceptedText 11373

我想要抓取的文字片段位于第一个":之间。在上面的例子中,它将是单词dial

这是我放在一起的脚本:

#!/usr/bin/perl

open (SESAME, '/home/my_name/whereMyFileLives.txt');
while (<SESAME>) {
  $text .= $_;
}
close (SESAME);

$text =~ /\n*$/;
$text =~ m/ \" (.*) :> /;

print $text;

当我运行此脚本时,它会将文件打印到终端,就像文件一样。它不会解析文本并提取我希望它提取的文本片段。

任何指针?

3 个答案:

答案 0 :(得分:1)

无法理解你为什么要与\n进行第一场比赛,但对于你的任务,你可以这样做:

my ($result) = $text =~ /\"([^:]*):/;

答案 1 :(得分:1)

my ($string) = $text =~ /"(.*?):/;

答案 2 :(得分:-1)

尝试:

#!/usr/bin/env perl

use strict;
use warnings;

# --------------------------------------

use charnames qw( :full :short );
use English qw( -no_match_vars ) ;  # Avoids regex performance penalty

# open (SESAME, '/home/my_name/whereMyFileLives.txt');
#
# Please use the three-argument open
my $sesame_file = '/home/my_name/whereMyFileLives.txt';
open my $sesame_fh, '<', $sesame_file or die "could not open $sesame_file: $OS_ERROR\n";

# while(<SESAME>)
while( my $line = <$sesame_fh> ){

# {
# $text .= $_;
# }
# close (SESAME);
# $text=~/\n*$/;
# $text=~m/ \" (.*) :> /;
# print $text;
#
# No need to store the complete text, just extract what you want from each line
    if( $line =~ m{ \" ( [^:]* ) \: }msx ){
        my $snippet = $1;
        print "$snippet\n";
    } # end if

} # end while
close $sesame_fh or die "could not close $sesame_file: $OS_ERROR\n";
相关问题