正则表达式在线工作但不在程序中

时间:2017-03-15 10:44:43

标签: java regex

我一直在研究可以解析字符串的正则表达式,例如:

(15-03-2017 11:12:47) nielsje41 [Niels] - this is a message
(15-03-2017 11:12:47) nielsje41 [Niels] - this is another message
(15-03-2017 11:12:47) nielsje41 [Niels] - testing (messages in parenthesis)

我想出了以下内容:(.+) (.+) \[(.+)\] - (.+)

在线正则表达式编译器上,这似乎工作正常:https://regex101.com/r/6Klht6/4

但是当我尝试在我的Java代码中实现它时,它找不到任何匹配项。

示例程序:

public class RegexDemo {

    private static final Pattern PATTERN = Pattern.compile("(.+) (.+) \\[(.+)\\] - (.+)");

    public static void main(String[] args) {
        String[] matchStrings = {
                "(15-03-2017 11:12:47) nielsje41 [Niels] - this is a message",
                "(15-03-2017 11:12:47) nielsje41 [Niels] - this is another message",
                "(15-03-2017 11:12:47) nielsje41 [Niels] - testing (messages in parenthesis)"
        };
        for (String str : matchStrings) {
            Matcher matcher = PATTERN.matcher(str);
            String dt = matcher.group(0);
            String user = matcher.group(1);
            String display = matcher.group(2);
            String message = matcher.group(3);
        }
    }
}

异常java.lang.IllegalStateException: No match found中的结果。我无法弄清楚为什么它不匹配,在线编译器似乎正在工作。任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要先致电matches以匹配您的模式,然后才能获得论坛。

public class RegexDemo {

    private static final Pattern PATTERN = Pattern.compile("(.+) (.+) \\[(.+)\\] - (.+)");

    public static void main(String[] args) {
        String[] matchStrings = {
                "(15-03-2017 11:12:47) nielsje41 [Niels] - this is a message",
                "(15-03-2017 11:12:47) nielsje41 [Niels] - this is another message",
                "(15-03-2017 11:12:47) nielsje41 [Niels] - testing (messages in parenthesis)"
        };
        for (String str : matchStrings) {
            Matcher matcher = PATTERN.matcher(str);
            if (matcher.matches()) {
                String dt = matcher.group(0);
                String user = matcher.group(1);
                String display = matcher.group(2);
                String message = matcher.group(3);

                System.out.println(dt);
                System.out.println(user);
                System.out.println(display);
                System.out.println(message);
            }
        }
    }
}