PatternSyntaxException 类在 Java 正则表达式中\n


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

更新日期:2020 年 1 月 10 日

94 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
宣传
© . All rights reserved.