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

4 Answers 4

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 \\] ?

Sign up to request clarification or add additional context in comments.

4 Comments

I had made the ]+? portion as reluctant but didn't know that has to make the .+ also as reluctant. Thank you
Bart's right, there shouldn't be a quantifier after the closing ] at all, much less a reluctant one.
how should be regex for following string - Ms Abc<[email protected]>;Mr Cde<[email protected]>;Miss Xyz<[email protected]>";so i can split the title, name and email id, thanks
@Apache, if you have a question of your own, I recommend creating a new question.
4

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

Pattern.compile("\\[.+?\\],?\\s*")
                      ^

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.