Home:ALL Converter>Validate Second Name using regex if the string contains hyphen

Validate Second Name using regex if the string contains hyphen

Ask Time:2020-11-20T18:15:35         Author:WideWood

Json Formatter

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?

Author:WideWood,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/64927599/validate-second-name-using-regex-if-the-string-contains-hyphen
yy