35

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

}
stema
  • 80,307
  • 18
  • 92
  • 121
amal
  • 3,160
  • 8
  • 25
  • 40

15 Answers15

97

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

stema
  • 80,307
  • 18
  • 92
  • 121
  • 1
    yes thats very true. This regex works perfectly. Smart one.thnx lot – amal Apr 04 '13 at 08:31
  • 7
    (based on stema's answer) how about this one: `"^\pL+[\pL\pZ\pP]{0,}"` now all dash, dot and space are also in unicode – Raheel Hasan Apr 04 '13 at 10:05
  • What does the "+" stand for? – Zen Jun 14 '16 at 07:29
  • @summers plus sign means one or more repetitions – slxl Jul 08 '16 at 10:24
  • `^[\\p{L}]+$` appears to mach all types of spaces also. Does spaces also fall under Unicode Character category? – Aamir Rizwan Jul 27 '17 at 08:38
  • @AamirRizwan no, '\p{L}' contains only any kind of letters and no whitespace. – stema Jul 27 '17 at 09:07
  • But it will consume `. ` as a name as well – Nick Sikrier Feb 12 '18 at 11:27
  • @NickSikrier I don't get your point. Of course it does, as the `.` is explicitly mentioned in the character class and I require only at least one character. It will also match a single space and `'` and `-`. This answer is only a starting point for those who think that they need to judge what is a valid name. Feel free to add a "better" quantifier than `+` to request a minimum/maximum length, or check with lookaheads for character sequences that make no sense for you (But maybe for the guy with the "exotic" name). – stema Feb 12 '18 at 11:44
  • @stema I am sorry, as a starting point, of course, it is a good example. Anyway, in most cases I suppose, it should, at least, start and finish with a letter. – Nick Sikrier Feb 12 '18 at 11:55
  • Strangely, this validates a name starting with spaces. – Prince Sep 18 '20 at 10:34
16

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.

Raheel Hasan
  • 5,044
  • 4
  • 33
  • 58
13

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
Ziza
  • 161
  • 1
  • 4
7

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
    }
Magnilex
  • 10,219
  • 8
  • 49
  • 72
Rahul Sahay
  • 71
  • 1
  • 1
4

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
}
Jaydeep Patel
  • 1,607
  • 14
  • 28
  • whats the difference between `[a-zA-Z][a-zA-Z ]*` and `[a-zA-Z][a-zA-Z ]+` ? did you know ? – Pardeep Jain Dec 12 '16 at 05:31
  • 1
    * mean optional(zero or more) and + meaning more then one. so suppose you check with single character then `[a-zA-Z][a-zA-Z ]*` will return true but for `[a-zA-Z][a-zA-Z ]+` returns false for that you need 2 characters. note: you can use `[a-zA-Z]+` instead of `[a-zA-Z][a-zA-Z ]*` both are equivalent. – Jaydeep Patel Dec 13 '16 at 11:12
3

Regex pattern for matching only alphabets and white spaces:

String regexUserName = "^[A-Za-z\\s]+$";
Rahul Raina
  • 2,883
  • 21
  • 27
2

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);
    }  
Krishnakant Kadam
  • 2,775
  • 1
  • 12
  • 8
1

To validate for only letters and spaces, try this

String name1_exp = "^[a-zA-Z]+[\-'\s]?[a-zA-Z ]+$";
NikolayK
  • 3,580
  • 3
  • 25
  • 37
Vijay Chauhan
  • 129
  • 1
  • 1
  • 6
1

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

}
Amit Vaghela
  • 21,317
  • 19
  • 79
  • 131
  • How is this better than accepted answer? This doesn't match `Peter Müller` or `François Hollande` – Toto Sep 15 '18 at 12:19
1

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

Rishabh876
  • 1,971
  • 1
  • 14
  • 31
0

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

}
0

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.

Nick Sikrier
  • 71
  • 1
  • 1
  • 5
  • Shouldn't it support Hindi names as well? like रोहित शर्मा . Any language character should be accepted right? But it's failing to identify Hindi type script Devanagari as Language character. – Rishabh876 Jul 15 '19 at 09:22
  • Unfortunately, it works correctly. Devanagari contains zero-width joiner, as it is complex script. https://en.wikipedia.org/wiki/Zero-width_joiner – Nick Sikrier Jul 31 '19 at 21:07
0

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

/^[A-z]*$|^[A-z]+\s[A-z]*$/
Purkhalo Alex
  • 1,929
  • 21
  • 18
0

Try with this:

public static boolean userNameValidation(String name){

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

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;
}