Java PatternSyntaxException Class getIndex() Method with Examples
Last Updated :
02 Feb, 2022
Java PatternSyntaxException Class is defined under the java.util.regex package and it depicts unchecked exception that signifies syntax error in a regular expression pattern. This class can be declared using the below syntax,
public class PatternSyntaxException extends IllegalArgumentException
PatternSyntaxException::getIndex()
This method is used to retrieve the index of the error which is thrown as an exception. The syntax is given below,
Syntax:
public int getIndex()
Returns: It returns a non-negative integer: The index in the pattern of the error is -1 if the index cannot be retrieved
Example 1: In this example, the error is at the index 0 in the pattern. This is because of the unclosed character.
Java
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
class GFG {
private static String regularExpression = "[" ;
private static String input = "GeeksforGeeks " + "is a learning platform." ;
private static String replace = "Hi" ;
public static void main (String[] args) {
try {
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(input);
input = matcher.replaceAll(replace);
} catch (PatternSyntaxException e){
System.out.println( "Index: " + e.getIndex());
System.out.println( "Message: " + e.getMessage());
}
}
}
|
Output
Index: 0
Message: Unclosed character class near index 0
[
^
Example 2: In this example, getIndex() method returns -1. This is because of illegal repetition the index cannot be retrieved.
Java
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
class GFG {
private static String regularExpression = "{" ;
private static String input = "GeeksforGeeks " + "is a learning platform." ;
private static String replace = "Hello" ;
public static void main (String[] args) {
try {
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(input);
input = matcher.replaceAll(replace);
} catch (PatternSyntaxException e){
System.out.println( "Index: " + e.getIndex());
System.out.println( "Message: " + e.getMessage());
}
}
}
|
Output
Index: -1
Message: Illegal repetition
{
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...