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
You don't need a
try...catchto 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 aif...elseblock:The PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern. This means that if your
NAME_REGEXregex has a syntax error then when you callPattern.compile(NAME_REGEX)this exception will be thrown.You can
try...catchit like: