HardCode
HardCode

Reputation: 2025

Cannot assign regex string in objective-c

I'm having issue assigning regex value to a string. Issue that I have is I have \d in the string value and objective-c complaining!

Here is my code

I'm assigning regex value here.

- (BOOL) validateUSZipCode: (NSString *) candidate {
   NSString *regex = @"^\d{5}(-\d{4})?$"; 
   NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; 

   return [test evaluateWithObject:candidate];
}

Someone help me please!

Upvotes: 1

Views: 581

Answers (1)

Rob Napier
Rob Napier

Reputation: 299683

You need to quote backslashes to include them in a constant NSString.

NSString *regex = @"^\\d{5}(-\\d{4})?$"; 

Upvotes: 2

Related Questions