NSPredicate with regex to check alphanumeric

风格不统一 提交于 2019-12-07 17:35:17

问题


I want to check string with regex in Objective c. My code

NSString *regexAmazonOrder =@"[a-zA-Z0-9]*";
NSPredicate *predicateAmazonOrder = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regexAmazonOrder];

if([predicateAmazonOrder evaluateWithObject:cardNumber.text])
{
    NSLog(@"Its coming inside AMAZON ORDER EVALUATIONS");
    ...
}

But its not working. Help me out. I know its simple but eating my mind!!! Thanks


回答1:


Try like this: (Untested, just to give you an starter)

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[a-z0-9]*"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];
NSArray *matches = [regex matchesInString:cardNumber.text
                                  options:0
                                    range:NSMakeRange(0, [string length])];

if([matches count] > 0)
{
   // Valid input
}



回答2:


Here is shorter version:

+(BOOL)isAlphanumericString:(NSString *)string
{
    NSString *filter = @"[a-z0-9]*";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", filter];
    return [predicate evaluateWithObject:string];
}


来源:https://stackoverflow.com/questions/17567243/nspredicate-with-regex-to-check-alphanumeric

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