PatternSyntaxException

java.util.regex.PatternSyntaxException Example

In this example we will discuss about java.util.regex.PatternSyntaxException. This exception is thrown when a regex (a regular exception) pattern is not correct, i.e. has syntax errors.

The PatternSyntaxException extends IllegalArgumentException, which means that an argument passed to a method is illegal or inappropriate. Just like IllegalArgumentException, PatternSyntaxException is a runtime exception (indirect subclass of RuntimeException). This means that the try-catch block is not required for this exception.

PatternSyntaxException exists since JDK 1.4.

The structure of PatternSyntaxException

Constructor:

  • PatternSyntaxException(String desc, String regex, int index)

    Constructs a new instance of PatternSyntaxException with a specified description, the regex that has the error, and the index of the error.

The PatternSyntaxException in Java

To see when the PatternSyntaxException is thrown, create a Java class called SimplePatternSyntaxExceptionExample with the following source code:

SimplePatternSyntaxExceptionExample.java

package com.javacodegeeks.examples;

import java.util.regex.Pattern;

public class SimplePatternSyntaxExceptionExample {
	
	public static void main(String... args) {
		String regex = "["; // invalid regex
		Pattern pattern = Pattern.compile(regex);
	}

}

In this example, I created an invalid regex, [, and passed it to Pattern.compile() in order to create a valid Pattern.

In our case, an exception will throw, since the regex is not valid. So, the output is this:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
	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.(Unknown Source)
	at java.util.regex.Pattern.compile(Unknown Source)
	at com.javacodegeeks.examples.SimplePatternSyntaxExceptionExample.main(SimplePatternSyntaxExceptionExample.java:9)

Also, the same exception is thrown by the Pattern.matches() method, if the regex passed as argument is invalid. See this example:

MatcherPatternSyntaxExceptionExample.java

package com.javacodegeeks.examples;

import java.util.regex.Pattern;

public class MatcherPatternSyntaxExceptionExample {

	public static void main(String[] args) {

		String text = "Lorem ipsum dolor sit amet, "
				+ "consectetur adipiscing elit, sed do "
				+ "eiusmod tempor incididunt ut labore "
				+ "et dolore magna aliqua";
		
		if (Pattern.matches("\\",text)) {
			System.out.println("This should not happen");
		}
	}

}

In this example, I passed another invalid regex, \ to the Pattern.matches() method. This results in the throwing of the PatternSyntaxException.

So, the output is this:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^
	at java.util.regex.Pattern.error(Unknown Source)
	at java.util.regex.Pattern.compile(Unknown Source)
	at java.util.regex.Pattern.(Unknown Source)
	at java.util.regex.Pattern.compile(Unknown Source)
	at java.util.regex.Pattern.matches(Unknown Source)
	at com.javacodegeeks.examples.MatcherPatternSyntaxExceptionExample.main(MatcherPatternSyntaxExceptionExample.java:14)

How to deal with PatternSyntaxException

If you encounter a PatternSyntaxException in the runtime, you should again revise the pattern used in your code and replace it with the proper one.

Also, you can surround the code with a try-catch block and use methods like getDescription() or getMessage() on the exception thrown.

In this last example, I will show how to catch the exception:

CatchPatternSyntaxException.java

package com.javacodegeeks.examples;

import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class CatchPatternSyntaxException {
	
	public static Pattern patternFromString(String str) {
		Pattern p = null;
		
		try {
			p = Pattern.compile(str);
			System.out.println("Pattern created: "+p.pattern());
		} catch (PatternSyntaxException ex) {
			System.out.println("This string could not compile: "+ex.getPattern());
			System.out.println(ex.getMessage());
		}
		
		return p;
	}
	
	public static void main(String[] args) {
		String question = "\\?";
		String invalid = "\\";
		
		Pattern questionPattern, invalidPattern;
		
		questionPattern = patternFromString(question);
		invalidPattern = patternFromString(invalid);
	}

}

Check the patternFromString() method which acts like a Pattern factory, and creates a Pattern instance out of a string. On lines 28 and 29, this method is invoked with two regular expressions, one of which is invalid. In this case, the method doesn’t throw an exception, causing the program to close. Instead, the exception is caught, and a message is printed for the user to read.

Download Code

Download
You can download the full source code of this example here : PatternSyntaxExceptionExample

Aldo Ziflaj

Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
avinash
avinash
5 years ago

Hi,

I am not a java programmer, I am a esql programmer while i am working with java I am getting below error:

ERROR: java.util.regex.PatternSyntaxException: Dangling meta character ‘*’

my input was : Test|x|***-5268-2569|2015-05-02

I am logging this value to file. But i am getting above error.
The main thing is i need to log the *** to in the log file.

Could you please help me with this.

Back to top button