问题
I create below code for Regex for name that contain Alphabets only
For Eg:
John -Correct
John123-Incorrect
John 123 - Incorrect
John Micheal -it shows incorrect as its have whitespace . How to fix it?
-(BOOL)validateNameWithString:(NSString*)nameStr
{
NSString *nameRegex = @"^[a-zA-Z]*$";
NSPredicate *testRegex = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
if(![testRegex evaluateWithObject:nameStr])
return NO;
else
return YES;
}
回答1:
Just add the whitespace token \s to the list of allowed tokens:
^[a-zA-Z\s]*$
check this working on Regex101
And as pointed out in the comments, you need to escape the backslash
NSString *nameRegex =@"^[a-zA-Z\\s]*$";
来源:https://stackoverflow.com/questions/40362688/regex-for-name-only-in-uitextfield