Java 正則表示式 - PatternSyntaxException 類



引言

java.util.regex.PatternSyntaxException 類表示丟擲以指示正則表示式模式中的語法錯誤的未檢查異常。

類宣告

以下是 java.util.regex.PatternSyntaxException 類的宣告 −

public class PatternSyntaxException
   extends IllegalArgumentException

構造方法

序號 方法和描述
1 PatternSyntaxException(String desc, String regex, int index)

構造此類的例項。

類方法

序號 方法和描述
1 String getDescription()

檢索錯誤的描述。

2 int getIndex()

檢索錯誤索引。

3 String getMessage()

返回一個多行字串,其中包含語法錯誤及其索引、錯誤正則表示式模式以及模式中錯誤索引的視覺化指示。

4 String getPattern()

檢索錯誤的正則表示式模式。

繼承的方法

此類繼承以下類的成員方法 −

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

範例

以下示例展示了 java.util.regex.Pattern.PatternSyntaxException 類方法的使用。

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());
      }
   }
}

讓我們編譯並執行上面的程式,這將產生以下結果 −

PatternSyntaxException: 
Description: Unclosed character class
Index: 0
Message: Unclosed character class near index 0
[
^
Pattern: [
© . All rights reserved.