Java : PatternSyntaxException (regex) 示例
PatternSyntaxException (Java SE 22 & JDK 22) 示例。
您将在大多数 PatternSyntaxException 方法中找到代码示例。
注解 :
- 本文可能使用了翻译软件以方便阅读。 另请查看英文原文。
简介
// 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
请参阅下面的链接。
相关文章
- API 示例