这里是一个文本文件。由Perl抓取文本
BEGIN:-----------------------------------------------
test 1
test 2 %%%%%%%%%% TEST TEST TEST
test 3
END:
我需要抓住标签BEGIN:
和END:
之间的文本。
我该如何用Perl以两种不同的方式做到这一点?
这里是一个文本文件。由Perl抓取文本
BEGIN:-----------------------------------------------
test 1
test 2 %%%%%%%%%% TEST TEST TEST
test 3
END:
我需要抓住标签BEGIN:
和END:
之间的文本。
我该如何用Perl以两种不同的方式做到这一点?
这个味道像家庭作业,所以我会给你一些方法来快速皮肤猫,但也许有更好的方法来做到这一点。
方法1
#!/usr/bin/perl
open FILE, "infile.txt"
# assuming bad formatting in the question and that BEGIN and END are on their own lines
my @text;
while (<FILE>)
if ($_ =~ /BEGIN:/) {
next;
} else if ($_ =~ /END:/) {
next;
} else {
push $_,@text;
}
close FILE
@Text是与所有的文本
方法2的阵列(这实际上是换行和回车的更foregiving)
#!/usr/bin/perl
$oldirs = $/;
$/=''; # set IRS to nothing
open FILE, "infile.txt";
$line = readline *FILE;
close FILE;
$line =~ s/BEGIN://g;
$line =~ s/END://g;
$/=$oldirs;
$line now contains all the text
非常感谢。 :) – Cristine 2011-04-14 01:11:07
这是触发器操作员的用途。 – 2011-04-14 02:04:33
另一替代...假设文字在$foo
...
$foo =~ /^BEGIN:([\S\s]+?)END:$/m;
result = $1;
OP的奖励积分...为什么$foo =~ /^BEGIN:(.+?)END:$/m
无法正常工作?
这是更好的方法;) – 2011-04-14 01:14:51
use common::sense;
local $/ = '';
my $file_content = <DATA>;
say $file_content;
say 'first result:';
say $file_content =~ /BEGIN:(.+?)END:/s;
say 'second result:';
my $begin = index($file_content,'BEGIN:') + 6;
my $end = index($file_content,'END:',$begin);
say substr($file_content,$begin,$end-$begin);
__DATA__
BEGIN:-----------------------------------------------
test 1
test 2 %%%%%%%%%% TEST TEST TEST
test 3
END:
欢迎堆栈溢出!你尝试了什么?什么没有用?应该怎样工作?你不明白什么?你明白了什么? – 2011-04-14 00:55:36
听起来有点像作业?为什么你需要两种不同的方式? – drewrockshard 2011-04-14 00:56:02
来自同一个人的第二个家庭作业问题。如果你不想学习编程,那么放下编程课。 http://stackoverflow.com/questions/5657581/extract-the-data-from-excel-file – tadmc 2011-04-14 01:36:01