Home > database >  How to split string by ' ' Except inside square brackets
How to split string by ' ' Except inside square brackets

Time:10-25

My example string: a [b*a c] c [ab c] and split by ' '

After split:

a
[b*a c]
c
[ab c]

I can do it for parentheses by using \\ (?![^()]*\\)) as regex into input.split(regex). But cant figure out for square brackets. I appreciate for any kind of help

CodePudding user response:

Negative lookahead is needed to match a except those put before the closing bracket \]

String str = "a [b*a c] c [ab c]";
String[] arr = str.split("\\ (?![^\\[]*\\])");

Arrays.stream(arr)
      .forEach(System.out::println);

Output

a
[b*a c]
c
[ab c]
  •  Tags:  
  • java
  • Related