Java多行正则表达式调试

时间:2012-12-21 10:40:29

标签: java regex multiline

在Java中,使用以下正则表达式

To: a@b\.com.*Subject: Please verify your email address

以某种方式在本文中找不到匹配项:

Dez 21, 2012 10:29:58 AM com.google.appengine.api.datastore.dev.LocalDatastoreService init
INFO: Local Datastore initialized: 
    Type: High Replication
    Storage: In-memory
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO: MailService.send
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO:   From: 
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO:   To: a@b.com
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO:   Subject: Please verify your email address
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO:   Body:
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO:     Content-type: text/plain
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO:     Data length: 4

我的Java代码如下所示:

    Matcher matcher = Pattern.compile(regex, Pattern.MULTILINE).matcher(input);
    if (matcher.find()) {
        ...
    }

这有点奇怪,因为当我使用此工具在线测试时,该模式似乎有效:http://regexpal.com

因此,Java必须以不同的方式解释模式。有没有办法获取Matcher的错误消息?

更新它应该找到:

To: a@b.com
Dez 21, 2012 10:29:58 AM com.google.appengine.api.mail.dev.LocalMailService log
INFO:   Subject: Please verify your email address

1 个答案:

答案 0 :(得分:9)

您需要使用Pattern.DOTALL代替Pattern.MULTILINE

DOTALL使.匹配换行符。 (这是你想要的)

MULTILINE使^$按行进行。