Search code examples
regexstringkotlinsplit

How to split string to substrings wrapped by brackets?


I have a string like this

[abc][def]

I've implemented following code to parse it:

val matches: MutableList<String> = mutableListOf()
val str = "[abc][def]"
val matcher = Pattern.compile("\\[([^]]+)]?").matcher(str)
while(matcher.find()) {
    matches.add(matcher.group(1));
}
println(matches)

this code leads to

enter image description here

But I want to get elements wrapped with brackets.

[abc] and [def]

How can I achieve it ?


Solution

  • You could use String#split() and split on the regex pattern (?<=\])(?=\[):

    String input = "[abc][def]";
    String[] parts = input.split("(?<=\\])(?=\\[)");
    System.out.println(Arrays.toString(parts));  // [[abc], [def]]
    

    The regex pattern uses lookarounds which say to split when:

    • (?<=\]) the previous character is a closing ]
    • (?=\[) the next character is an opening [