📜  Java正则表达式-PatternSyntaxException类

📅  最后修改于: 2020-11-14 10:19:27             🧑  作者: Mango


介绍

java.util.regex.PatternSyntaxException类表示引发的未经检查的异常,该异常表示正则表达式模式中的语法错误。

类声明

以下是java.util.regex.PatternSyntaxException类的声明-

public class PatternSyntaxException
   extends IllegalArgumentException

建设者

Sr.No Method & Description
1 PatternSyntaxException(String desc, String regex, int index)

Constructs a new instance of this class.

类方法

Sr.No Method & Description
1 String getDescription()

Retrieves the description of the error.

2 int getIndex()

Retrieves the error index.

3 String getMessage()

Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.

4 String getPattern()

Retrieves the erroneous regular-expression pattern.

方法继承

此类从以下类继承方法-

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