java.util.regex.PatternSyntaxException: Unmatched closing ‘)’

The regular expression uses the “( )” round bracket to identify the matching groups in a string. The matched character in the round bracket identified as a match group in a string. The exception “java.util.regex.PatternSyntaxException: Unclosed group near index” will be thrown if the close round bracket is available without a open round bracket.

Exception in thread "main" java.util.regex.PatternSyntaxException: Unmatched closing ')'
)
	at java.util.regex.Pattern.error(Pattern.java:1955)
	at java.util.regex.Pattern.compile(Pattern.java:1700)
	at java.util.regex.Pattern.<init>(Pattern.java:1351)
	at java.util.regex.Pattern.compile(Pattern.java:1028)
	at java.lang.String.replaceAll(String.java:2223)
	at com.yawintutor.StringReplaceAll.main(StringReplaceAll.java:9)


Root Cause

The close round bracket “)” is added in the regular expression without having open round bracket. Either the regular expression group is created using open round bracket “(” along with close round bracket “)” or the close round bracket should be escaped to match the character.



How to reproduce this issue

The example below contains regular expression with a close round bracket and without open round bracket. The below program throws the exception.

package com.yawintutor;

public class StringReplaceAll {
	public static void main(String[] args) {
		String str = "Washington(50)";
		String pattern = ")";
		String str2;

		str2 = str.replaceAll(pattern, "");

		System.out.println("Given  String : " + str);
		System.out.println("Output String : " + str2);
	}
}


Solution 1

The close bracket should be added with escape character as shown in the below program.

package com.yawintutor;

public class StringReplaceAll {
	public static void main(String[] args) {
		String str = "Washington(50)";
		String pattern = "\\)";
		String str2;

		str2 = str.replaceAll(pattern, "");

		System.out.println("Given  String : " + str);
		System.out.println("Output String : " + str2);
	}
}

Output

Given  String : Washington(50)
Output String : Washington(50


Solution 2

If the regular expression is created to match group, then the appropriate open round bracket should be added to match with close round bracket.



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *