Java Regex - PatternSyntaxException Class



Introduction

The java.util.regex.PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern.

Class declaration

Following is the declaration for java.util.regex.PatternSyntaxException class −

public class PatternSyntaxException
   extends IllegalArgumentException

Constructors

Sr.No Method & Description
1 PatternSyntaxException(String desc, String regex, int index)

Constructs a new instance of this class.

Class methods

Sr.No Method & Description
1 String getDescription()

Retrieves the description of the error.

2 int getIndex()

Retrieves the error index.

3 String getMessage()

Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.

4 String getPattern()

Retrieves the erroneous regular-expression pattern.

Methods inherited

This class inherits methods from the following classes −

  • Java.lang.Throwable
  • Java.lang.Object

Example

The following example shows the usage of java.util.regex.Pattern.PatternSyntaxException class methods.

package com.tutorialspoint; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class PatternSyntaxExceptionDemo { private static String REGEX = "["; private static String INPUT = "The dog says meow " + "All dogs say meow."; private static String REPLACE = "cat"; public static void main(String[] args) { try{ Pattern pattern = Pattern.compile(REGEX); // get a matcher object Matcher matcher = pattern.matcher(INPUT); INPUT = matcher.replaceAll(REPLACE); } catch(PatternSyntaxException e){ System.out.println("PatternSyntaxException: "); System.out.println("Description: "+ e.getDescription()); System.out.println("Index: "+ e.getIndex()); System.out.println("Message: "+ e.getMessage()); System.out.println("Pattern: "+ e.getPattern()); } } }

Let us compile and run the above program, this will produce the following result −

PatternSyntaxException: 
Description: Unclosed character class
Index: 0
Message: Unclosed character class near index 0
[
^
Pattern: [
Advertisements