Java string.split("(") throws unclosed group near index 1 an exception

String is widely used object in any java project,In some cases we may need to split the string using open bracket "(" or closed bracket. If we do that we get exception like Unclosed group near index 1.
java.util.regex.PatternSyntaxException: Unclosed group near index 1
 at java.util.regex.Pattern.error(Pattern.java:1924)
 at java.util.regex.Pattern.accept(Pattern.java:1782)
 at java.util.regex.Pattern.group0(Pattern.java:2857)
 at java.util.regex.Pattern.sequence(Pattern.java:2018)
 at java.util.regex.Pattern.expr(Pattern.java:1964)
 at java.util.regex.Pattern.compile(Pattern.java:1665)
 at java.util.regex.Pattern.<init>(Pattern.java:1337)
 at java.util.regex.Pattern.compile(Pattern.java:1022)
 at java.lang.String.split(String.java:2313)
 at java.lang.String.split(String.java:2355)

We need to escape the literals before we split as like below. We will not get the exception any more.
String s = "Hello(SplitTest";
String ss[] = s.split("\\(");


Post a Comment

Powered by Blogger.