In this article, we try to address a frequently encountered error with regular expression in java :
PatternSyntaxException: Unclosed character class
The following example demonstrates this :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.regex.Matcher; import java.util.regex.Pattern; public class Hello { public static void main(String[] args) { String regex = "[a-zA-Z\\]*$"; String value = "hello"; boolean match = validateRegex(regex, value); System.out.println(match); } private static boolean validateRegex(String regex, String value) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(value); return matcher.matches(); } } |
Output :
Exception in thread “main” java.util.regex.PatternSyntaxException: Unclosed character class near index 10 The issue is because of Unclosed character class, i.e, you have opened class of characters but never closed it. In this case, the character class was opened with [ character and the program tried to close it with ]. However, the \\ before it escaped it’s special meaning and its treated as a normal character. To fix it, simply, remove the escape character as shown below :
[a-zA-Z\]*$
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.clazz(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.
at java.util.regex.Pattern.compile(Unknown Source)
at Hello.validateRegex(Hello.java:14)
at Hello.main(Hello.java:9)Output:
true
If you want to use ] as a normal character to be allowed, you can use \\]]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.regex.Matcher; import java.util.regex.Pattern; public class Hello { public static void main(String[] args) { String regex = "[a-zA-Z\\]]*$"; String value = "hello]"; boolean match = validateRegex(regex, value); System.out.println(match); } private static boolean validateRegex(String regex, String value) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(value); return matcher.matches(); } } |
Output:
true
© 2018, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post