-2

How do I write a regular expression for a name?

I would like it to validate The following examples:

Albert Einstein

ALBERT EINSTEIN

ALBert EINstein

alberT einstIN

Ale'rt E'i'n't'e'in

These should all be considered valid.

This is what I have so far, but it fails:

-(BOOL) validateName: (NSString *) name{
    
    NSString *nameRegex = @"(?:[A-Z]+[a-z' '])"; 
    NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
    return [nameTest evaluateWithObject:name];
} 

Can anyone suggest an improvement?

1
  • 1
    You can't "validate" an actual name with a simple regular expression, you can only validate what you decide is acceptable. There are plently of names with more than two words, unusual characters, perhaps even a number! Take for example: Billy-Bob James O'Brien Ⅻ
    – Mog
    Oct 12, 2011 at 19:42

3 Answers 3

0

The right Regular Expression is this one: ^[a-zA-Z ]+$

This Regular Expression recognize alle the word containing lower/capital letters separated by spaces.

You can test your Regular Expression here

5
  • I want to add one more Giuseppe it can take This example Albe'rt E'i'n't'e'in
    – user891268
    Oct 12, 2011 at 12:21
  • This regular expression will help me lot too
    – user891268
    Oct 12, 2011 at 12:24
  • 1
    If you want to add ' in the range of valid characters just add this inside the square braces. i.e. : ^[a-zA-Z ']+$
    – Giuseppe
    Oct 12, 2011 at 12:26
  • 1
    You will need more than that to make this actually useful for a real person's name. -1 For claiming this is the "right" regex (there really isn't one).
    – Mog
    Oct 12, 2011 at 19:40
  • I think the question was clear, He want to recognize a name providing a validation list. My answer is correct: the regular expression recognize the names present in his list and I also provide a link in order to test this result.
    – Giuseppe
    Oct 13, 2011 at 10:29
0

If you wrap your expression in

(?ismwx-ismwx: ... )

Flag settings. Evaluate the parenthesized expression with the specified flags enabled or -disabled. The flags are defined in “Flag Options.”

Case insensitive flag is i.

Or you can use

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"albert einstein" options:NSRegularExpressionCaseInsensitive error:&error];

But you'll need to specify the context where names appear to have something general...

0

^[A-Za-z]+(\s[A-Za-z]+)*$

It works with

`Albert, Albert Einstein, Edison Arantes do Nascimento aka Pele

If you need exactly 2 words use:

^[A-Za-z]+\s[A-Za-z]+$

Not the answer you're looking for? Browse other questions tagged or ask your own question.