首頁  >  文章  >  Java  >  Java正規表示式中的PatternSyntaxException類

Java正規表示式中的PatternSyntaxException類

WBOY
WBOY轉載
2023-09-11 19:37:021189瀏覽

Java正規表示式中的PatternSyntaxException類

PatternSyntaxException 類別表示在正規表示式字串中出現語法錯誤時引發的未經檢查的例外狀況。這個類別包含三個主要方法,即 -

  • getDescription() - 傳回錯誤的描述。

    li>
  • 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: [

以上是Java正規表示式中的PatternSyntaxException類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除