-1

I've been working on a regex which can parse strings such as:

(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)

I came up with the following: (.+) (.+) \[(.+)\] - (.+)

On the online regex compiler this seems to work fine: https://regex101.com/r/6Klht6/4

But when I try to implement it in my Java code it can't find any matches.

Example program:

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);
        }
    }
}

Results in exception java.lang.IllegalStateException: No match found. I can't figure out why it doesn't match, the online compiler looks to be working. Any suggestions would be greatly appreciated.

nbokmans
  • 5,492
  • 4
  • 35
  • 59

1 Answers1

1

You need to call matches to match your pattern before you can get the groups.

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);
            }
        }
    }
}
alturkovic
  • 990
  • 8
  • 31