2011-04-14 32 views
-5

這裏是一個文本文件。由Perl抓取文本

BEGIN:----------------------------------------------- 
test 1 
test 2 %%%%%%%%%% TEST TEST TEST 
test 3 
END: 

我需要抓住標籤BEGIN:END:之間的文本。

我該如何用Perl以兩種不同的方式做到這一點?

+6

歡迎堆棧溢出!你嘗試了什麼?什麼沒有用?應該怎樣工作?你不明白什麼?你明白了什麼? – 2011-04-14 00:55:36

+1

聽起來有點像作業?爲什麼你需要兩種不同的方式? – drewrockshard 2011-04-14 00:56:02

+3

來自同一個人的第二個家庭作業問題。如果你不想學習編程,那麼放下編程課。 http://stackoverflow.com/questions/5657581/extract-the-data-from-excel-file – tadmc 2011-04-14 01:36:01

回答

0

這個味道像家庭作業,所以我會給你一些方法來快速皮膚貓,但也許有更好的方法來做到這一點。

方法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 
+0

非常感謝。 :) – Cristine 2011-04-14 01:11:07

+1

這是觸發器操作員的用途。 – 2011-04-14 02:04:33

0

另一替代...假設文字在$foo ...

$foo =~ /^BEGIN:([\S\s]+?)END:$/m; 
result = $1; 

OP的獎勵積分...爲什麼$foo =~ /^BEGIN:(.+?)END:$/m無法正常工作?

+0

這是更好的方法;) – 2011-04-14 01:14:51

3

只問Perl文檔:

我怎麼可以拉了兩次 模式,本身就 不同線路之間的線路?

perldoc -q between

0
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: