Java Regex to Validate Full Name allow only Spaces and Letters

I want regex to validate for only letters and spaces. Basically this is to validate full name. Ex: Mr Steve Collins or Steve Collins I tried this regex. "[a-zA-Z]+\.?" But didnt work. Can someone assist me please p.s. I use Java.

public static boolean validateLetters(String txt) {

    String regx = "[a-zA-Z]+\\.?";
    Pattern pattern = Pattern.compile(regx,Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(txt);
    return matcher.find();

}

What about:

  • Peter Müller
  • François Hollande
  • Patrick O'Brian
  • Silvana Koch-Mehrin

Validating names is a difficult issue, because valid names are not only consisting of the letters A-Z.

At least you should use the Unicode property for letters and add more special characters. A first approach could be e.g.:

String regx = "^[\\p{L} .'-]+$";

\\p{L} is a Unicode Character Property that matches any kind of letter from any language


try this regex (allowing Alphabets, Dots, Spaces):

"^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]{0,}$" //regular
"^\pL+[\pL\pZ\pP]{0,}$" //unicode

This will also ensure DOT never comes at the start of the name.


For those who use java/android and struggle with this matter try:

"^\\p{L}+[\\p{L}\\p{Z}\\p{P}]{0,}"

This works with names like

  • José Brasão

You could even try this expression ^[a-zA-Z\\s]*$ for checking a string with only letters and spaces (nothing else).

For me it worked. Hope it works for you as well.

Or go through this piece of code once:

    CharSequence inputStr = expression;
    Pattern pattern = Pattern.compile(new String ("^[a-zA-Z\\s]*$"));
    Matcher matcher = pattern.matcher(inputStr);
    if(matcher.matches())
    {
         //if pattern matches
    }
    else
    {
         //if pattern does not matches
    }

please try this regex (allow only Alphabets and space)

"[a-zA-Z][a-zA-Z ]*"

if you want it for IOS then,

NSString *yourstring = @"hello";

NSString *Regex = @"[a-zA-Z][a-zA-Z ]*";
NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];

if ([TestResult evaluateWithObject:yourstring] == true)
{
    // validation passed
}
else
{
    // invalid name
}