Javaregex 简明教程

Java Regex - PatternSyntaxException Class

Introduction

java.util.regex.PatternSyntaxException 类表示抛出一个未检查异常,以指示正则表达式模式的语法错误。

The java.util.regex.PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern.

Class declaration

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

Following is the declaration for java.util.regex.PatternSyntaxException class −

public class PatternSyntaxException
   extends IllegalArgumentException

Constructors

Sr.No

Method & Description

1

*PatternSyntaxException(String desc, String regex, int index)*Constructs a new instance of this class.

Class methods

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.

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. Java.lang.Throwable

  2. Java.lang.Object

Example

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

The following example shows the usage of java.util.regex.Pattern.PatternSyntaxException class methods.

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

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

PatternSyntaxException:
Description: Unclosed character class
Index: 0
Message: Unclosed character class near index 0
[
^
Pattern: [