【问题标题】:ios: Checking regular expression with NSPredicate - Unable to parse the format stringios:使用 NSPredicate 检查正则表达式 - 无法解析格式字符串
【发布时间】:2014-09-18 16:19:36
【问题描述】:

我正在尝试使用正则表达式验证 iOS 中的用户名。为此,我使用了 NSPredicate,但它引发了运行时错误。

这是我的 ViewController 中的内容:

@property (nonatomic, strong) NSString *userNamePattern;

还有:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
    _userNamePattern = @"[a-zA-Z0-9_-]{3,20}";

然后在一个动作中点击按钮时:

  NSPredicate *userNameTest = [NSPredicate predicateWithFormat:self.userNamePattern];

在底线它抛出了这个错误:

   *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "[a-zA-Z0-9_-]{3,20}"'

为什么不这样?

【问题讨论】:

    标签: ios regex nspredicate


    【解决方案1】:

    您只是将正则表达式模式传递给谓词。你需要给它一个实际的谓词格式字符串。

    为你的谓词试试这个:

    NSPredicate *userNameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", self.userNamePattern];
    

    【讨论】:

    • 啊,就是这样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多