如何检查字符串是否与perl中的正则表达式匹配?

时间:2011-07-30 08:31:31

标签: regex perl if-statement

我遇到了perl的问题。我想解析一个电子邮件对象或日志或文件。我想找到邮件来自哪里。首先我必须检查“x-envelop-from”行,如果不匹配,那么我必须检查“从”行。

这是我的一些示例文件:

X-Envelope-From: 
    <kamil@yahoo.com>
From: "=?iso-8859-9?B?RXYgVGH+/W1hY/1s/fD9bmRhIsdfyhjdbmRRmltIFNlem9u?=
    =?iso-8859-9?B?dQ==?=" <kamil@yahoo.com>

我的代码为此文件打印了2行:

kamil@yahoo.com
kamil@yahoo.com

锄头是可能的,两个印刷线都打印在if和elsif?检查比赛有问题吗?

while ( $line = <FILE>) 
{
    my ($from, $to, $spam_id, $date, $tmp_date, $m_day, $m_mon, $m_year, $m_hour, $m_min, $pos_tmp);
    my ($subject);
# 
    if ( $line =~ m/^(X-Envelope-From:).*/ ) {
        if ( $line =~ m/^X-Envelope-From:.*<(.*)>.*/ ) {
            $from = $1;
        }
        else {
            $line = <FILE>;
            if ( $line =~ m/.*<(.*)>.*/ ) {
                $from = $1;
            }
        }
        print $from . "\n";
    }

    elsif ( $line =~ m/^(From:).*/ ) {
        if ( $line =~ m/^From:.*<(.*)>.*/ ) {
            $from = $1;
        }
        else {
            $line = <FILE>;
            if ( $line =~ m/.*<(.*)>.*/ ) {
                $from = $1;
            }
        }
        print $from . "\n";
    }
}

提前感谢。

1 个答案:

答案 0 :(得分:6)

使用Email::MIME等专用模块来解析标题:

#!/usr/bin/env perl

use strict;
use warnings;

use Email::MIME;

my $em = Email::MIME->new(
    do { local $/; <DATA> }
);

my $from = $em->header('X-Envelope-From');
$from = $em->header('From') unless $from;

$from =~ s{.*<|>.*}{}g;
print $from;

__DATA__
X-Envelope-From: 
    <kamil@yahoo.com>
From: "=?iso-8859-9?B?RXYgVGH+/W1hY/1s/fD9bmRhIsdfyhjdbmRRmltIFNlem9u?=
    =?iso-8859-9?B?dQ==?=" <kamil@yahoo.com>