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
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
}
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