Java : PatternSyntaxException (regex) with Examples

PatternSyntaxException (Java SE 22 & JDK 22) with Examples.
You will find code examples on most PatternSyntaxException methods.


Summary

Unchecked exception thrown to indicate a syntax error in a regular-expression pattern.

Class diagram

// OK
final var pattern = Pattern.compile("[a-z]");
final var predicate = pattern.asPredicate();

System.out.println(predicate.test("abc")); // true
System.out.println(predicate.test("123")); // false

// NG
try {
    var _ = Pattern.compile("[a-z");
} catch (PatternSyntaxException e) {
    System.out.println("PatternSyntaxException! : " + e.getMessage());
}

// Result
// ↓
//PatternSyntaxException! : Unclosed character class near index 3
//[a-z
//   ^

Constructors

PatternSyntaxException (String desc, String regex, int index)

Constructs a new instance of this class.

final var e = new PatternSyntaxException("abc", "xyz", 10);
System.out.println(e);

// Result
// ↓
//java.util.regex.PatternSyntaxException: abc near index 10
//xyz

System.out.println(e.getDescription()); // abc
System.out.println(e.getPattern()); // xyz
System.out.println(e.getIndex()); // 10

Methods

String getDescription ()

Retrieves the description of the error.

final var e = new PatternSyntaxException("abc", "xyz", 10);
System.out.println(e);

// Result
// ↓
//java.util.regex.PatternSyntaxException: abc near index 10
//xyz

System.out.println(e.getDescription()); // abc
System.out.println(e.getPattern()); // xyz
System.out.println(e.getIndex()); // 10

int getIndex ()

Retrieves the error index.

final var e = new PatternSyntaxException("abc", "xyz", 10);
System.out.println(e);

// Result
// ↓
//java.util.regex.PatternSyntaxException: abc near index 10
//xyz

System.out.println(e.getDescription()); // abc
System.out.println(e.getPattern()); // xyz
System.out.println(e.getIndex()); // 10

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.

final var e = new PatternSyntaxException("abc", "xyz", 10);
System.out.println(e.getMessage());

// Result
// ↓
//abc near index 10
//xyz

String getPattern ()

Retrieves the erroneous regular-expression pattern.

final var e = new PatternSyntaxException("abc", "xyz", 10);
System.out.println(e);

// Result
// ↓
//java.util.regex.PatternSyntaxException: abc near index 10
//xyz

System.out.println(e.getDescription()); // abc
System.out.println(e.getPattern()); // xyz
System.out.println(e.getIndex()); // 10

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page