Mikhail Zinkovsky
Mikhail Zinkovsky

Reputation: 156

Regular expression pattern does not work in Objective-C

I need to check wether my string matches this regular expression pattern: \+?\d{0,3} (This pattern has been tested here: http://regexpal.com and it seems all right.)

This is what I do:

NSString * proposedNewString = @"+3";    
NSString * pattern = @"\\+?\\d{0,3}";
NSError * err = nil;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&err];
if (err) {
    NSLog(@"Couldn't create regex with given string and options");
    return NO;
}

NSPredicate * myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES '%@'", regex];

NSLog(@"proposed str = %@", proposedNewString);
if ([myTest evaluateWithObject:proposedNewString]) {
    NSLog(@"yes");
}
else {
    NSLog(@"no");
}

I expect it to print out yes, but for some reason it prints no. Maybe I messed up the backslashes or quotes. What am I doing wrong?

Upvotes: 0

Views: 905

Answers (1)

Martin R
Martin R

Reputation: 540075

The "MATCHES" operator in a predicate format expects as argument a pattern string, not a regular expression (and you must not enclose %@ in quotation marks). So this produces the expected result "yes":

NSString * proposedNewString = @"+3";    
NSString * pattern = @"\\+?\\d{0,3}";
NSPredicate * myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
if ([myTest evaluateWithObject:proposedNewString]) {
    NSLog(@"yes");
} else {
    NSLog(@"no");
}

Alternatively, use one of the NSRegularExpression methods instead of a predicate, for example

if ([regex numberOfMatchesInString:proposedNewString options:0 range:NSMakeRange(0, [proposedNewString length])] > 0) {
    NSLog(@"yes");
} else {
    NSLog(@"no");
}

Upvotes: 1

Related Questions