[java] 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();

}

This question is related to java regex validation

The answer is


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.


Validates such values as: "", "FIR", "FIR ", "FIR LAST"

/^[A-z]*$|^[A-z]+\s[A-z]*$/

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
}

This works for me with validation of bootstrap

$(document).ready(function() {
$("#fname").keypress(function(e) {
var regex = new RegExp("^[a-zA-Z ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
 return true;
}

@amal. This code will match your requirement. Only letter and space in between will be allow, no number. The text begin with any letter and could have space in between only. "^" denotes the beginning of the line and "$" denotes end of the line.

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();

}

Accept only character with space :-

 if (!(Pattern.matches("^[\\p{L} .'-]+$", name.getText()))) {
    JOptionPane.showMessageDialog(null, "Please enter a valid character", "Error", JOptionPane.ERROR_MESSAGE);
    name.setFocusable(true);
    }  

check this out.

String name validation only accept alphabets and spaces
public static boolean validateLetters(String txt) {

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

}

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

Regex pattern for matching only alphabets and white spaces:

String regexUserName = "^[A-Za-z\\s]+$";

My personal choice is: ^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$, Where:

^\p{L}+ - It should start with 1 or more letters.

[\p{Pd}\p{Zs}'\p{L}]* - It can have letters, space character (including invisible), dash or hyphen characters and ' in any order 0 or more times.

\p{L}+$ - It should finish with 1 or more letters.

|^\p{L}+$ - Or it just should contain 1 or more letters (It is done to support single letter names).

Support for dots (full stops) was dropped, as in British English it can be dropped in Mr or Mrs, for example.


To support language like Hindi which can contain /p{Mark} as well in between language characters. My solution is ^[\p{L}\p{M}]+([\p{L}\p{Pd}\p{Zs}'.]*[\p{L}\p{M}])+$|^[\p{L}\p{M}]+$

You can find all the test cases for this here https://regex101.com/r/3XPOea/1/tests


To validate for only letters and spaces, try this

String name1_exp = "^[a-zA-Z]+[\-'\s]?[a-zA-Z ]+$";

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
    }

Try with this:

public static boolean userNameValidation(String name){

return name.matches("(?i)(^[a-z])((?![? .,'-]$)[ .]?[a-z]){3,24}$");
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery