Home > Java > javaTutorial > PatternSyntaxException class in Java regular expressions

PatternSyntaxException class in Java regular expressions

WBOY
Release: 2023-09-11 19:37:02
forward
1230 people have browsed it

PatternSyntaxException class in Java regular expressions

PatternSyntaxException Class represents an unchecked exception thrown when a syntax error occurs in a regular expression string. This class contains three main methods, namely -

  • getDescription() - Returns the description of the error.

    li>
  • getIndex() - Returns the error index.

  • getPattern() - Returns the regular expression pattern in which the error occurred.

  • getMessage() - Returns the complete message containing the error, the index, the regular expression pattern in which the error occurred, and the error in the indicated pattern.

Example

Real-time demonstration

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

Output

Enter a String
this is a [sample text [
Description: Unclosed character class
Index: 0
Message: Unclosed character class near index 0
[
^
Pattern: [
Copy after login

The above is the detailed content of PatternSyntaxException class in Java regular expressions. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template