I’m stuck on this problem for quite a while now and I couldn’t figure out a proper solution with the usual google search. I’m trying to evaluate the format of a string, more precisely I’m checking to see if the string is a Canadian postal code or not.
So I started with this regex, thanks to geeks with blogs
^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
After that, I’ve created an instance of NSRegularExpression in such way:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[ABCEGHJKLMNPRSTVXY]{1}\\d{1}[A-Z]{1} *\\d{1}[A-Z]{1}\\d{1}$" options:NSRegularExpressionCaseInsensitive error:&error];
With added backslashes for escaping.
Then I made an NSPredicate with the regular expression
NSPredicate *regextest = [NSPredicate
predicateWithFormat:@"SELF MATCHES[cd] %@", regex];
And finally, I’m evaluating the string itself
[regextest evaluateWithObject:@"G2G 2S2"]
At that last line, an exception is thrown.
NSInvalidArgumentException Can’t create a regex expression from object
NSRegularExpression: 0x81e1bb0 ^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1}
*\d{1}[A-Z]{1}\d{1}$ 0x1.
I can’t figure it out =/ I tested the regex itself with a regex tester and it’s fine, and from what I checked with google that’s how a string evaluation should be done. I’m at lost here. Anyone have an idea?
In an
NSPredicatethe pattern is just a string, so this will work:Oh, and I agree that the
{1}-parts should be removed – they just add clutter.