【发布时间】:2011-07-24 00:25:59
【问题描述】:
我有一个邮箱文件,其中包含超过 50 兆的消息,由以下内容分隔:
从 - 2007 年 7 月 19 日星期四 07:11:55
我想在 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);
这个正则表达式正确还是我解析文件不正确?
【问题讨论】:
标签: java regex java.util.scanner