Regex for Name Only in UITextfield

雨燕双飞 提交于 2019-12-11 04:10:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!