Setting up NSPredicate with a phrase and number sequence

85 Views Asked by At

I'm sorry if this is an overly specific question. Tried searching for basic help with NSPredicate and getting nowhere.

I'm trying to validate a string that should begin with a particular word (let's say it's SPOT, in all caps) and is followed by exactly 4 numeric digits.

In other words, for example, SPOT1234 or SPOT0483 would pass validation. SPAT1234, spot1234, SPOT123 or any other string would fail.

Can anyone point me in the right direction?

3

There are 3 best solutions below

1
On BEST ANSWER

You can use an NSPredicate with a regular expression.

NSArray *testArray = @[@"SPOT1234", @"SPOT0483", @"SPAT1234", @"spot1234", @"SPOT123", @"SPOT1233232"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '^SPOT\\\\d{4}$'"];
NSArray *resultsArray = [testArray filteredArrayUsingPredicate:predicate];

The resultsArray will contain two strings: SPOT1234, SPOT0483

0
On

Try this :

NSArray *arrStr = @[@"SPOT1212",@"spot1234",@"SPOT12233"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"self LIKE \"SPOT????\""]];
NSArray *filterArr = [arrStr filteredArrayUsingPredicate:predicate];
3
On

You can use NSRegularExpression as @Larme said like this:

- (BOOL)validateString:(NSString *)string {
    return [string rangeOfString:@"^SPOT\\d{4}$" options:NSRegularExpressionSearch].location != NSNotFound;
}

NSLog(@"%d", [self validateString:@"SPOT123456789"]);  // false
NSLog(@"%d", [self validateString:@"SPAT1234"]);       // false
NSLog(@"%d", [self validateString:@"spot1234"]);       // false
NSLog(@"%d", [self validateString:@"SPOT123"]);        // false
NSLog(@"%d", [self validateString:@"SPOT0483"]);       // true