regex for splitting a string while ignoring the brackets [duplicate]

You can use the below regex to achieve your requirement:

[ ](?=[^\)]*?(?:\(|$))

Explanation of the above regex:

[ ] – Represents a space character.

(?=[^\)]*?(?:\(|$)) – Represents a positive look-ahead asserting everything inside of ().

(?:) – Represents a non-capturing group.

| – Represents alternation.

$ – Represents the end of the test String.

You can find the demo of the above regex in here.

Pictorial representation


import java.util.Arrays;
public class Main
    public static void main(String[] args) {
        String s = "hello (split this) string";
        String reg = "[ ](?=[^\\)]*?(?:\\(|$))";

// output: [hello, (split this), string]

You can find the above implementation here.

Leave a Comment