电子邮件标题消息的正则表达式

时间:2011-07-24 00:25:59

标签: java regex java.util.scanner

我有一个邮箱文件,其中包含50多条消息,分隔如下:

From - Jul 7月19日07:11:55 2007

我想在Java中为此构建一个正则表达式,以便一次提取一封邮件,因此我尝试使用扫描程序,使用以下模式作为分隔符:

public boolean ParseData(DataSource data_source) {

    boolean is_successful_transfer = false;
    String mail_header_regex = "^From\\s";
    LinkedList<String> ip_addresses = new LinkedList<String>();
    ASNRepository asn_repository = new ASNRepository();

    try {       

    Pattern mail_header_pattern = Pattern.compile(mail_header_regex);

    File input_file = data_source.GetInputFile();

    //parse out each message from the mailbox
    Scanner scanner = new Scanner(input_file);      

    while(scanner.hasNext(mail_header_pattern)) {


    String current_line = scanner.next(mail_header_pattern);

    Matcher mail_matcher = mail_header_pattern.matcher(current_line);

        //read each mail message and extract the proper "received from" ip address 
        //to put it in our list of ip's we can add to the database to prepare
        //for querying.
        while(mail_matcher.find()) {
            String message_text = mail_matcher.group();                 
            String ip_address = get_ip_address(message_text);

            //empty ip address means the line contains no received from
            if(!ip_address.trim().isEmpty()) 
                ip_addresses.add(ip_address);
        }

    }//next line

        //add ip addresses from mailbox to database 
        is_successful_transfer = asn_repository.AddIPAddresses(ip_addresses);           

    }

    //error reading file--unsuccessful transfer
    catch(FileNotFoundException ex) {
        is_successful_transfer = false;
    }

    return is_successful_transfer;

}

这似乎应该可行,但每当我运行它时,程序都会挂起,可能是由于它没有找到模式。这个相同的正则表达式在Perl中使用相同的文件,但在Java中它始终挂在String current_line = scanner.next(mail_header_pattern);

这个正则表达式是正确的还是我正确解析文件?

1 个答案:

答案 0 :(得分:1)

通过阅读,我会倾向于更简单的 ,这样的事情:

while(scanner.hasNextLine()) {
    String line = scanner.nextLine();
    if (line.matches("^From\\s.*")) {
       // it's a new email
    } else {
       // it's still part of the email body
    }
}