Fix: java.util.regex.PatternSyntaxException


package org.code2care.example;

public class PatternSyntaxExceptionExample {

    public static void main(String[] args) {

        String string = "1(2(3(4(5";
        String[] strArr = string.split("(");


Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 1
	at java.base/java.util.regex.Pattern.error(
	at java.base/java.util.regex.Pattern.accept(
	at java.base/java.util.regex.Pattern.group0(
	at java.base/java.util.regex.Pattern.sequence(
	at java.base/java.util.regex.Pattern.expr(
	at java.base/java.util.regex.Pattern.compile(
	at java.base/java.util.regex.Pattern.<init>(
	at java.base/java.util.regex.Pattern.compile(
	at java.base/java.lang.String.split(
	at java. base/java.lang.String.split(
	at org.code2care.example.JavaSplitOnDotStringExample2.main(

Reason for the exception:

The java.lang.String split() function throws a PatternSyntaxException if the if the regular expression's syntax is invalid.

If you take a closer look at the regular expression used here open braces (, this has a special meaning when working with Regular Expressions. Such characters need to be escaped with a double forward slash \\


Change the regex string from,




Below is the list of all the characters that when you want to use "literally" in the regex string needs to be escaped.

\Escape character
.Any character except a newline
+One or more occurrences
*Zero or more occurrences
?Zero or one occurrence
(Start of a capturing group
)End of a capturing group
[Start of a character class
]End of a character class
{Start of a quantifier
}End of a quantifier
-Range of characters in a class
^Start of a string/line
$End of a string/line

Facing issues? Have Questions? Post them here! I am happy to answer!

Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap