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.
IMPLEMENTATION IN JAVA
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
String s = "hello (split this) string";
String reg = "[ ](?=[^\\)]*?(?:\\(|$))";
System.out.println(Arrays.toString(s.split(reg)));
}
}
// output: [hello, (split this), string]
You can find the above implementation here.
3
solved regex for splitting a string while ignoring the brackets [duplicate]