tags:

views:

86

answers:

3

Hi,

I want to split the string

String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";

to

name
employeeno
dob
joindate

I wrote the following java code for this but it is printing only name other matches are not printing.

String fields = "name[Employee Name], employeeno[Employee No], dob[Date of Birth], joindate[Date of Joining]";

Pattern pattern = Pattern.compile("\\[.+\\]+?,?\\s*" );

String[] split = pattern.split(fields);
for (String string : split) {
    System.out.println(string);
}

What am I doing wrong here?

Thank you

+4  A: 

This part:

\\[.+\\]

matches the first [, the .+ then gobbles up the entire string (if no line breaks are in the string) and then the \\] will match the last ].

You need to make the .+ reluctant by placing a ? after it:

Pattern pattern = Pattern.compile("\\[.+?\\]+?,?\\s*");

And shouldn't \\]+? just be \\] ?

Bart Kiers
I had made the ]+? portion as reluctant but didn't know that has to make the .+ also as reluctant. Thank you
Arun P Johny
@Arun, you're welcome.
Bart Kiers
Bart's right, there shouldn't be a quantifier after the closing `]` at all, much less a reluctant one.
Alan Moore
+4  A: 

The error is that you are matching greedily. You can change it to a non-greedy match:

Pattern.compile("\\[.+?\\],?\\s*")
                      ^
Mark Byers
+1  A: 

There's an online regular expression tester at http://gskinner.com/RegExr/?2sa45 that will help you a lot when you try to understand regular expressions and how they are applied to a given input.

Philipp Jardas