- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PatternSyntaxException class in Java regular expressions
The PatternSyntaxException class represents an unchecked exception thrown in case of a syntax error in regex string. This class contains three main methods namely −
getDescription() − Returns the description of the error.
getIndex() − Returns the error index.
getPattern() − Returns the regular expression pattern with error.
getMessage() − Returns the complete message congaing the error, index, regular expression pattern with error, indication of the error in the pattern.
Example
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()); } } }
Output
Enter a String this is a [sample text [ Description: Unclosed character class Index: 0 Message: Unclosed character class near index 0 [ ^ Pattern: [
Advertisements