首页 > 文章列表 > Java正则表达式中的PatternSyntaxException类

Java正则表达式中的PatternSyntaxException类

Java正则表达式 pattern SyntaxException
300 2023-09-02

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