2011-03-05 46 views
3

我寫了一個Perl程序,它從文本文件中讀取文本並將其打印出來。Perl正則表達式問題

我想打印出一個具有特定格式的行。

例如,有這樣的句子:

information: 
Ahmad.prn:592118:2001:7:5:/Essay 
Ashford.rtf:903615:2001:6:28:/usr/Essay 
Barger.doc:243200:2001:7:4:/home/dir 
end of Information. 

我只想閱讀這些三行:

Ahmad.prn:592118:2001:7:5:/Essay 
Ashford.rtf:903615:2001:6:28:/usr/Essay 
Barger.doc:243200:2001:7:4:/home/dir 

我認爲字段的含義是:

Ahmad.prn <- file name 
592118 <- size of file 
2001:7:5 <- created date 
/Essay <- path of file 

我的代碼是這樣的:

#!/usr/bin/perl 
use strict; 
use warnings; 

open (my $infh, "<", $file)||die "cant open"; 

while(my $line = <$infh>) { 
    chomp ($line); 
    if ($line =~ /(what regular expression do I have to put in here?)/) { 
     print "$line"; 
    } 
} 

close ($infh); 
+1

你確實需要提供更多關於你想要實現的信息。 – dalton 2011-03-05 12:12:13

+1

請清楚說明線路格式是什麼。目前還不清楚你是否只想刪除第一行和最後一行,只匹配以/ Essay結尾的行,匹配匹配a:b:c:d:e:f ....的行。 – Mat 2011-03-05 12:20:49

回答

4

如果你需要經常用行/徵文結束後,您可以使用正則表達式如下

/:\/Essay$/ 

編輯1:看上去有中間部分只有數字,你可以匹配這個樣子。

/:\d+:\d+:\d+:\d+:/ 
+0

not alwyas end with essay ...還有其他的詞 – misaka 2011-03-05 12:15:54

+0

我認爲符號是'filename:filesize:date:path'em ..'〜' – misaka 2011-03-05 12:20:42

+0

@misaka,所以,中間部分只有數字?增加了另一個正則表達式 – YOU 2011-03-05 12:22:15

1
$line =~ m{ 
^
    (\w+\.\w+) # filename stored as $1 
    : 
    (\d+) # size stored as $2 
    : 
    (\d{4}) # year stored as $3 
    : 
    (\d+) # month stored as $4 
    : 
    (\d+) # day stored as $5 
    : 
    (.*) # path stored as $6 
    $ 
    }x 
1

既然你有這樣的格式Ahmad.prn:592118:2001年:7:5:/隨筆

Ahmad.prn <- file name 
592118 <- size of file 
2001:7:5 <- created date 
/Essay <- path of file 

你可以使用這個正則表達式

/^\s*(\S+):(\d+):(\d+:\d+:\d+):(\S+)\s*$/ 

有了這個,您將擁有文件名稱$ 1,文件大小$ 2,創建日期$ 3,文件路徑$ 4

我加在該行的開始和結束的可選空間,如果你想允許可選的空間之前或之後:多個通過它的循環:您可以添加\ S *

1
#!/usr/bin/perl 
use strict; 

my $inputText = qq{ 
Ahmad.prn:592118:2001:7:5:/Essay 
Ashford.rtf:903615:2001:6:28:/usr/Essay 
Barger.doc:243200:2001:7:4:/home/dir 
end of Information. 
}; 

my @input = split /\n/, $inputText; 
my $i = 0; 
while ($input[$i] !~ /^end of Information.$/) { 
    if ($input[$i] !~ /:/) { 
     $i++; 
     next; 
    } 
    my ($fileName, $fileSize, $year, $month, $day, $filePath) = split /:/, $input[$i]; 
    print "$fileName\t $fileSize\t $month/$day/$year\t $filePath\n"; 
    $i++; 
} 
1
$line =~ ([a-zA-Z.]+):(\d+):(\d+):(\d+):(\d+):([\/A-Za-z]+) 

$name = $1; #Ahmad.prn 
$id = $2; #592118 
$year = $3; #2001 
$dir = $6; #/Essay 

註名稱