我有一个这样的文本文件这是垃圾行这是垃圾line2这是垃圾line3 message1这是第一行文本这是第二行文本这是第三行文本这是第四行文本这是第五行文本message1_end下一行
我想从message1开始执行模式匹配,然后在停止模式匹配后打印message1和message1_end之间的文本。
如何在perl中做到这一点??
提前感谢
森蒂尔。
发布于 2010-08-24 17:54:33
也许这对你有用。
open(YOURFILE,"./input.txt");
while (<YOURFILE>) {
if (/message1/ .. /message1_end/) {
printf "%s",$_;
}
}
close(YOURFILE);发布于 2010-08-24 18:20:11
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;发布于 2010-08-24 19:01:28
我不认为我们会得到这个问题的完美答案,因为它是如此模糊,但这里。
正如perldoc所解释的,您可以使用捕获缓冲区来简化您的工作。简而言之,您可以在正则表达式中引用文本组(()中的块),方法与初始化后相同,只需使用反斜杠(\)而不是美元符号($)来引用它们。
这段代码假设您可以访问整个可搜索缓冲区。如果您想逐行执行此操作,则需要有一个标记计数器(或其他类似机制),以确保您可以处理递归字符串(假设消息块本身可以包含消息块)
#!/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",..)。
https://stackoverflow.com/questions/3555209
复制相似问题