Java - Regex for Full Name

Nicholas Lie picture Nicholas Lie · Sep 9, 2011 · Viewed 45k times · Source

How can I validate regex for full name? I only want alphabets (no numericals) and only spaces for the regex. This is what I have done so far. Would you please help me fix the regex? Thank you very much

public static boolean isFullname(String str) {
    boolean isValid = false;
    String expression = "^[a-zA-Z][ ]*$"; //I know this one is wrong for sure >,<
    CharSequence inputStr = str;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        isValid = true;
    }
    return isValid;
}

Answer

jefflunt picture jefflunt · Sep 9, 2011

This problem of identifying names is very culture-centric, and it really has no hope of working reliably. I would really recommend against this, as there is NO canonical form for what makes up a person's name in any country, anywhere on Earth that I know of. I could legally change my name to #&*∫Ω∆ Smith, and that's not going to fit into anyone's algorithm. It's not that this specific example is something that a lot of people do, but many people don't think outside of the ASCII table when considering data input, and that's going to lead to problems.

You can argue against the probability of this happening, but in a global world, it's increasingly unlikely that ALL of your users are going to have English-transliterated spellings for their names. It's also very possible that you'll have users from cultures that don't have a concept of first/last name. Don't assume that, even if your application is only running in a given country, that some of your users won't be from other places (people move from country to country all the time, and some of them might want to use your software).

Protect your app against SQL injection for fields such as this (if you're storing these in a DB), and leave it at that.