regex - 多行正则表达式搜索

标签 regex perl grep textwrangler

在对 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/

相关文章:

javascript - 替换第 n 次出现的 javascript

perl - 从数组中获取奇数

linux - 当存在歧义时使用grep从linux中的txt文件中提取文本

regex - 正则表达式只匹配行尾的 X 个字符

regex - 构建正则表达式

sql - scala正则表达式提取sql语句中的字段子句

perl - 如果我要在 Perl 中使用纯 OO,是否需要 Exporter?

perl - 如何在列表中拆分管道分隔的字符串?

bash - 如何使用 Bash 检查文件是否包含特定字符串

bash - 在 grep 之后添加文本到每行的开头