Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx Split on / Except when Surrounded by []

Tags:

java

regex

I am trying to split a string in Java on / but I need to ignore any instances where / is found between []. For example if I have the following string

/foo/bar[donkey=King/Kong]/value

Then I would like to return the following in my output

  • foo
  • bar[donkey=King/Kong]
  • value

I have seen a couple other similar posts, but I haven't found anything that fits exactly what I'm trying to do. I've tried the String.split() method and as follows and have seen weird results:

Code:  value.split("/[^/*\\[.*/.*\\]]")

Result:  [, oo, ar[donkey=King, ong], alue]

What do I need to do in order to get back the following:

Desired Result:  [, foo, bar[donkey=King/Kong], value]

Thanks, Jeremy

like image 567
jwmajors81 Avatar asked Mar 22 '26 17:03

jwmajors81


1 Answers

You need to split on the / followed by an 0 or more balanced pairs of brackets:

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]

More User friendly 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
like image 146
Rohit Jain Avatar answered Mar 25 '26 07:03

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!