DarkLeafyGreen
DarkLeafyGreen

Reputation: 70406

How to make a regex check in objective-c

I have following regex check in javascript and I want to do the same in objective-c

if(/^[0-9]+$/.test(name)){  
    if(name.ength > 16) valid = false;
    if(name.substring(0,2) != "00") valid = false;
    return valid;
}

So in objective-c I tried it like this:

BOOL valid = true;

NSString *regex1 = @"/^[0-9]+$/";
NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex1];

if([test1 evaluateWithObject:name]){
    if([name length] > 16){
        valid = false;
    }

    if([name rangeOfString:@"00"].location == NSNotFound){
        valid = false;
    }
}

But the if body is never entered. Any ideas?

Upvotes: 2

Views: 280

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

Drop the slashes - you need them as delimiters in PHP, but not in Objective-C (they would attempt to match a literal slash, which obviously will fail):

NSString *regex1 = @"^[0-9]+$";

Upvotes: 1

Related Questions