简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM