mikea
mikea

Reputation: 6667

How to split a string for regex containing lookbehind and lookahead

I want to split the following string:

"VALUE:VALUE,VALUE:[VALUE1,VALUE2,VALUE3],VALUE:VALUE"

into

"VALUE:VALUE"
"VALUE:[VALUE1,VALUE2,VALUE3]"
"VALUE:VALUE"

I expected:

String[] elements = text.split("(?<!\\[),|,(?!\\])");

to get me part way there as I thought this meant that it wouldn't match a comma if it had a bracket before or after it but this returns:

"VALUE:VALUE"
"VALUE:[VALUE1"
"VALUE2"
"VALUE3]"
"VALUE:VALUE"

Any ideas how to do this?

Upvotes: 1

Views: 348

Answers (1)

Jerry
Jerry

Reputation: 71538

If you don't have any possibility of nesting, try this regex:

String[] elements = text.split(",(?![^\\[]*\\])");

This matches a comma which is not followed by a ] without any [ before it.

ideone demo

Upvotes: 2

Related Questions