Java : PatternSyntaxException (regex) with Examples
PatternSyntaxException (Java SE 22 & JDK 22) with Examples.
You will find code examples on most PatternSyntaxException methods.
Summary
// 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)
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 ()
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 ()
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 ()
final var e = new PatternSyntaxException("abc", "xyz", 10);
System.out.println(e.getMessage());
// Result
// ↓
//abc near index 10
//xyz
String getPattern ()
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
- API Examples