该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[]) { //从用户读取字符串 System.out.println("Enter a String"); Scanner sc = new Scanner(System.in);String input = sc.nextLine(); //正则表达式匹配单词的前几个数字 String regex = "["; //\\s+ //编译正则表达式 try { Pattern pattern = Pattern.compile(regex); //检索匹配器对象 Matcher matcher = pattern.matcher(input); //用单个空格替换所有空格字符 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: [