Perl 模式匹配

问题描述 投票:0回答:5

我有一个这样的文本文件 这是一条垃圾线 这是一条垃圾线路2 这是一条垃圾线路3 消息1 这是第一行文字 这是第二行文字 这是第三行文字 这是第四行文字 这是第五行文字 消息1_结束 下一行

我想从

message1
开始模式匹配,然后打印
message1
message1_end
之间存在的文本,之后应该停止模式匹配。

如何在 Perl 中执行此操作?

提前致谢

森希尔。

regex perl
5个回答
3
投票

也许这对你有用。

open(YOURFILE,"./input.txt");
while (<YOURFILE>) {
        if (/message1/ .. /message1_end/) {
                printf "%s",$_;
        }
}
close(YOURFILE);

3
投票
use strict;
use warnings;

open my $fh, '<', 'filename' or die "can't open 'filename' for reading : $!"
while(<$fh>) {
    chomp;
    if(/^message1$/ .. /^message1_end$/) {
        print $_,"\n" unless($_ eq 'message1' or $_ eq 'message1_end');
    }
}
close $fh;

1
投票

我认为我们不会得到这个问题的完美答案,因为它太模糊了,但就这样吧。

正如 perldoc 所解释的,您可以使用 capture buffers 来简化您的工作。 简而言之,您可以在正则表达式中引用文本组(

()
内的块),就像在初始化之后一样。您只需通过反斜杠 (\) 而不是美元符号 ($
) 来引用它们。
此代码假设您可以访问整个可搜索缓冲区。如果您想逐行执行此操作,您需要有一个标记计数器(或其他类似的机制)以确保您可以处理递归字符串(假设您的消息块本身可以包含消息块)

#!/usr/bin/perl use warnings; use strict; my $buf = 'this is a junk line this is a junk line2 this is a junk line3 message1 this is first line of text this is second line of text this is third line of text this is fourth line of text this is fifth line of text message1_end the next line'; if($buf =~m/(message\d)(.*?)(\1_end)/sg) { my $message = $2; # ... }

在这里,
\d
匹配单个数字(请参阅 perldoc 链接),并且

\1

 的计算结果与 
$1
("message1") 相同。由于开始标记与结束标记仅相差“_end”,因此我们使用开始标记来创建我们要查找的结束标记。通过这样做,代码将可以很好地处理多个消息(“message1”,“message2”,..)。

你可以这样做:

-1
投票
open F,"<","input.txt" or die; # try to open the file. while(<F>) { # loop through each line of the file. last if(/^message1_end\n$/); # break if message end is found. $messsage.=$_ if($start); # append to message $start = 1 if(/^message1\n$/); # set start to 1 to start appending. } print $messsage;

如果输入文件适合内存,另一种方法:

-2
投票
#!/usr/bin/perl local $/=undef; open FILE, "input.txt" or die "Couldn't open file: $!"; $string = <FILE>; close FILE; print $1 if ($string =~ /message1(.*)message1_end/sm);


© www.soinside.com 2019 - 2024. All rights reserved.