PatternSyntaxException 类表示在正则表达式字符串中出现语法错误时引发的未经检查的异常。该类包含三个主要方法,即 -
-
getDescription() - 返回错误的描述。
li>
-
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: [
登录后复制
以上就是Java正则表达式中的PatternSyntaxException类的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!