I need to validate first 开发者_运维知识库and last name from Credit card. For example: "Lange Norton" or "LANGE NORTON" I use this code:
NSString *nameRegex = @"^[A-Z][a-z]*[\pL\pM\p{Nl}][A-Z][a-z]*$";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
return [nameTest evaluateWithObject:nameSurname];
And I have a problem with whitespace. "Unknown escape sequence '\p'" What should I do?
I think you missed some curly brackets
NSString *nameRegex = @"^[A-Z][a-z]*[\p{L}\p{M}\p{Nl}][A-Z][a-z]*$";
if you also need whitspace add \s
You can find a list of those properties (the \p{L}\p{M}\p{Nl}
stuff) here on regular-expressions.info
\p{L} or \p{Letter}: any kind of letter from any language
\p{M} or \p{Mark}: a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.).
\p{Nl} or \p{Letter_Number}: a number that looks like a letter, such as a Roman numeral.
Additionally I don't think your expression is correct.
Your string needs to start with [A-Z]
followed by [a-z]*
(can also be zero) and then only one of those [\p{L}\p{M}\p{Nl}]
another uppercase ASCII letter followed by lowercase letters.
What happens if the persons name is "René Müller"?
You should find the correct escape sequence that will match whitespaces.
Try \s
instead of \p
.
Not sure where you got \p
as an escape sequence, but as the error says, it's not valid.
[EDIT] actually, it is valid, but not in the way you're using it.
The correct escape sequence for whitespace is \s
. This matches any valid whitespace character (there are quite a number of them, not just normal spaces).
However since you're validating only ASCII characters anyway, you could just as easily use a regular space character - ie no escaping required; just press the space bar on your keyboard. That is a perfectly valid character to match in a regex string.
Try this one:
([^\s]+)\s([^\s]+)(.*)
Don't forget to escape the \s in objective-c:
NSString *nameRegex = @"([^\\s]+)\\s([^\\s]+)(.*)";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
return [nameTest evaluateWithObject: nameSurname];
This checks for [anything not a space], then [a space], then [anything not a space], then [anything]
Wont work with name such as "宮本茂"
Will include names written like "John Smith (lots of spaces) Jr"
I agree with Spudley, but if you insist on validating the name, you should allow for several names on the card. This will validate for an unlimited number of names.
[\sA-Za-z]+
Mb \p{L}
- it means any character from Unicode letters, but I don't know, does your regex engine support this.
There is really a lot more to name validation than crafting a regex. Here's a PHP natural name parser:
nameparser
If I can't find an Objective C port, I'll do it my self and post it here.
EDITED 2/7/2013:
Here's my port for your coding pleasure:
NameParser.h
NameParser.m
精彩评论