I have a problem with validating second name using regex in Java.
I use Pattern.compile method to compile the given regular expression into a pattern. And Pattern.mathcer method to create a matcher that will match the given input against this pattern.
I need to validate second name if string contains hyphen.
This is my function to validate:
/**
* Determines if the string is valid and returns result code
*
* @param fio string to validate
* @return 1 - valid second name, name, patronymic; 2 - valid second name, name; 0 - invalid string
*/
public static int Validate(String fio) {
Pattern pattern;
Matcher matcher;
try {
pattern = Pattern.compile("([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+"); //second name; name; patronymic
matcher = pattern.matcher(fio);
if (matcher.matches()) return 1;
pattern = Pattern.compile("([A-Z])[a-z]+ ([A-Z])[a-z]+"); //second name; name
matcher = pattern.matcher(fio);
if (matcher.matches()) return 2;
} catch (PatternSyntaxException ex1) {
System.out.println("String is incorrect!");
}
return 0;
}
Could you tell me how to change my regex string pattern to validate second name with hyphen?