PatternSyntaxException 類在 Java 正則表示式中\n
**PatternSyntaxException** 類表示在正則表示式字串中出現語法錯誤時丟擲的未檢查異常。此類包含三個主要方法,具體如下 -
getDescription() - 返回錯誤描述。
getIndex() - 返回錯誤索引。
getPattern() - 返回帶有錯誤的正則表示式模式。
getMessage() - 返回包含錯誤、索引、帶有錯誤的正則表示式模式以及模式中錯誤指示的完整訊息。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class PatternSyntaxExceptionExample {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);String input = sc.nextLine();
//Regular expression to match first digits of a word
String regex = "["; //\s+
//Compiling the regular expression
try {
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
//Replacing all space characters with single space
String result = matcher.replaceAll(" ");
System.out.print("Text after removing unwanted spaces: \n"+result);
}catch(PatternSyntaxException ex){
System.out.println("Description: "+ex.getDescription());
System.out.println("Index: "+ex.getIndex());
System.out.println("Message: "+ex.getMessage());
System.out.println("Pattern: "+ex.getPattern());
}
}
}輸出
Enter a String this is a [sample text [ Description: Unclosed character class Index: 0 Message: Unclosed character class near index 0 [ ^ Pattern: [
宣傳
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP