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
  • 161,055
  • 37
  • 262
  • 269
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520

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
  • 161,100
  • 35
  • 287
  • 281
4

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

Pattern.compile("\\[.+?\\],?\\s*")
                      ^
Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
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,082
  • 3
  • 27
  • 41
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,081
  • 1
  • 25
  • 38