在对 SO 和 Google 进行了大量搜索之后,我求助于发布一个新问题。我正在与 TextWrangler 合作,尝试编写一个正则表达式,它会为我提供多行模式的最短匹配。
基本上,
ہے\tVM
是我要查找的字符串(一个阿拉伯语单词,由制表符与其词性标记分隔)。困难的是我想搜索包含该字符串的所有单个句子。这是我目前所拥有的:
/(<Sentence id='\d+'>(?:[^<]|<(?!\/Sentence>))*ہے\tVM(?:[^<]|<(?!\/Sentence>))*<\/Sentence>)/
我正在查看的文件是用 CML 编码的,所以我的部分问题是你们中是否有人知道用于 MAC 的 CML 解析器?
另一个明显的替代方法是编写 Perl 脚本——在这里,我再次感谢任何指向简单解决方案的建议。
我当前的脚本是:
use open ':encoding(utf8)';
use Encode;
binmode(STDOUT, ":utf8");
binmode(STDIN, ":utf8");
my $word = Encode::decode_utf8("ہے");
my @files = glob("*.posn");
foreach my $file (@files) {
open FILE, "<$file" or die "Error opening file $file ($!)";
my $file = do {local $/; <FILE>};
close FILE or die $!;
if ($file =~ /(<Sentence id='\d+'>(?:[^<]|<(?!\/Sentence>))*$word\tVM(?:[^<]|<(?!\/Sentence>))*<\/Sentence>)/g) {
print STDOUT "$1\n\n\n\n";
push(@matches, "$1\n\n");
}
}
open(OUTPUT, ">matches.txt");
print OUTPUT "@matches";
close(OUTPUT);
最佳答案
您可能在输入中出现了更多的字符串,因此搜索所有这些......
我相信你的代码应该是这样的>>
use open ':encoding(utf8)';
use Encode;
binmode(STDOUT, ":utf8");
binmode(STDIN, ":utf8");
my $word = Encode::decode_utf8("ہے");
my @files = glob("*.posn");
my @matches = ();
foreach my $file (@files) {
open FILE, "<$file" or die "Error opening file $file ($!)";
my $file = do {local $/; <FILE>};
close FILE or die $!;
my @occurrences = $file =~ /<Sentence id='\d+'>(?:[^<]|<(?!\/Sentence>))*$word\tVM(?:[^<]|<(?!\/Sentence>))*<\/Sentence>/g;
print STDOUT "$_\n\n\n\n" for (@occurrences);
push (@matches, "$_\n\n") for (@occurrences);
}
open (OUTPUT, ">matches.txt");
print OUTPUT "@matches";
close(OUTPUT);
了解有关正则表达式的更多信息 here .
关于regex - 多行正则表达式搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13396940/