1

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

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531

4 Answers4

5

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
  • 166,582
  • 36
  • 299
  • 288
4

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

Pattern.compile("\\[.+?\\],?\\s*")
                      ^
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

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
  • 3,222
  • 3
  • 29
  • 42
0

WOuld it be better to use Negated Character Classes to match the square brackets? \[(\w+\s)+\w+[^\]]\]

You could also see a good example how does using a negated character class work internally (without backtracking)?

Community
  • 1
  • 1
r0n9
  • 2,505
  • 1
  • 29
  • 43