Home > OS >  how pattern syntax exception works
how pattern syntax exception works

Time:09-21

private static final String NAME_REGEX = "^[a-zA-Z] (([',. -][a-zA-Z ])?[a-zA-Z]*)*$";
 
private static final Pattern NAME_PATTERN = Pattern.compile(NAME_REGEX);

how do I use the following statement in try n catch block to chk if the name is valid and display error msg if any?

NAME_PATTERN.matcher(name).matches()

and how to use PatternSyntaxException

CodePudding user response:

You don't need a try...catch to check if the name is valid. The line you wrote: NAME_PATTERN.matcher(name).matches() returns a boolean, true if it matches and false if it doesn't. So you can check this boolean in a if...else block:

    boolean matches = NAME_PATTERN.matcher(name).matches();
    if (matches) {
        System.out.println("valid");
    } else {
        System.out.println("invalid");
    }

The PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern. This means that if your NAME_REGEX regex has a syntax error then when you call Pattern.compile(NAME_REGEX) this exception will be thrown.

You can try...catch it like:

public static void main(String[] args) {

    try {
        final String NAME_REGEX = "^[a-zA-Z] (([',. -][a-zA-Z ])?[a-zA-Z]*)*$";
        final Pattern NAME_PATTERN = Pattern.compile(NAME_REGEX);

        String name = "sdasdada"; //the name input
        boolean matches = NAME_PATTERN.matcher(name).matches();
        if (matches) {
            System.out.println("valid");
        } else {
            System.out.println("invalid");
        }
    } catch(PatternSyntaxException e){
        System.out.println("PatternSyntaxException: ");
        System.out.println("Description: "  e.getDescription());
        System.out.println("Index: "  e.getIndex());
        System.out.println("Message: "  e.getMessage());
        System.out.println("Pattern: "  e.getPattern());
    }
    
}
  • Related