UITextfield 中仅用于名称的正则表达式 [英] Regex for Name Only in UITextfield

查看:19
本文介绍了UITextfield 中仅用于名称的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为仅包含字母的名称创建了以下正则表达式代码

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;

    }

推荐答案

只需将空白标记 \s 添加到允许的标记列表中:

Just add the whitespace token \s to the list of allowed tokens:

^[a-zA-Z\s]*$

检查这个正在使用 Regex101

正如评论中指出的,你需要转义反斜杠

And as pointed out in the comments, you need to escape the backslash

NSString *nameRegex =@"^[a-zA-Z\\s]*$";

这篇关于UITextfield 中仅用于名称的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆