RegEx Split on / Except when surrounded by []
I'm trying to split a string in Java into /, but I need to ignore any instances where / is between []. For example, if I have the following line
/foo/bar[donkey=King/Kong]/value
Then I would like to return the following in my issue
- Foo
- bar [donkey = King / Kong]
- value
I have seen a couple of other similar posts, but I have not found anything that matches exactly what I am trying to do. I tried the String.split () method and as follows and saw strange results:
Code: value.split("/[^/*\\[.*/.*\\]]")
Result: [, oo, ar[donkey=King, ong], alue]
What do I need to do to get back to the next one:
Desired Result: [, foo, bar[donkey=King/Kong], value]
Thanks Jeremy
You need to split by /
and then by 0 or more balanced parenthesis pairs:
String str = "/foo/bar[donkey=King/Kong]/value";
String[] arr = str.split("/(?=([[^\\[\\]]*\\[[^\\[\\]]*\\])*[^\\[\\]]*$)");
System.out.println(Arrays.toString(arr));
Output:
[, foo, bar[donkey=King/Kong], value]
Read more Convenient explanation
String[] arr = str.split("(?x)/" + // Split on `/`
"(?=" + // Followed by
" (" + // Start a capture group
" [^\\[\\]]*" + // 0 or more non-[, ] character
" \\[" + // then a `[`
" [^\\]\\[]*" + // 0 or more non-[, ] character
" \\]" + // then a `]`
" )*" + // 0 or more repetition of previous pattern
" [^\\[\\]]*" + // 0 or more non-[, ] characters
"$)"); // till the end
On the next line, the regex will match foo and bar , but not fox and baz because they are followed by a close parenthesis. Explore the negative view.
fox]foo/bar/baz]
Regex:
\b(\w+)\b(?!])