Problem with patterns in java

This is not related to any game I’m developing, so that’s why I don’t post it here.

Here is my pattern code

Matcher m = Pattern.compile("\\[((.*?),|)(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})(,(.*?)|)\\]").matcher(text);

The problem I have with it that I want to be able to write things like this
[text,2014-09-09 19:00:00]
[text,2014-09-09 19:00:00,text]
[2014-09-09 19:00:00,text]
[2014-09-09 19:00:00]

What I want to happen is.
((.?),|) = Return any text without the “,” or null
(,(.
?)|) = Return any text without the “,” or null
(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) = Returns time and date in, yyyy-mm-dd hour:min:sec format

When I test with this [2014-09-09 19:00:00] I get these group
0: [2014-09-09 19:00:00]
1:
2: null
3: 2014-09-09 19:00:00
4:

and I can’t understand why group 4 isn’t null like group 2

Because it’s like group 1. Group 5 is like group 2 (null). Check the documentation of groupCount() - it doesn’t include group 0. If you use a for loop you need to use <=

I also tried altering your regex a little bit - not sure if it’s better :-\


        String text = "[testBefore,2014-09-09 19:00:00,testAfter]";
        String regex = "\\[((.*),)?(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})(,(.*))?\\]";
        Matcher m = Pattern.compile(regex).matcher(text);
        if (m.matches()) {
            for (int i=0; i<=m.groupCount(); i++) {
                System.out.println(i +":"+m.group(i));
            }
        } else {
            System.out.println("No match");
        }
        
        text = "[2014-09-09 19:00:00]";
        m = Pattern.compile(regex).matcher(text);
        if (m.matches()) {
            for (int i=0; i<=m.groupCount(); i++) {
                System.out.println(i +":"+m.group(i));
            }
        } else {
            System.out.println("No match");
        }

Output is

0:[testBefore,2014-09-09 19:00:00,testAfter]
1:testBefore,
2:testBefore
3:2014-09-09 19:00:00
4:,testAfter
5:testAfter
0:[2014-09-09 19:00:00]
1:null
2:null
3:2014-09-09 19:00:00
4:null
5:null

Nice little challenge for the afternoon. :wink:

Thanks so much, It works flawlessly. I had no idea ? could be used with groups.