My app is consistently crashing when I try to run an NSPredicate with a string containing a parenthesis. Here is the example code:
NSString *myString = @"test)";
NSPredicate *defaultPredicate = [NSPredicate predicateWithFormat:@"title MATCHES[cd] %@", myString];
Here is the resulting crash log:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't do regex matching, reason: Can't open pattern U_REGEX_MISMATCHED_PAREN (string test, pattern test), case 1, canon 2)
In my use case people should not be searching strings with parenthesis so I can sanitize the string by doing something like the code below but that is not elegant.
myString = [[myString stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""];
Any help or clues will be very appreciated. Thanks!
Best How To :
MATCHES is used for regular expression comparisons. Your expression is treated as a regular expression. And it will fail if your expression isn't a valid regex. So you generally don't want unfiltered user-input if you use
MATCHES, because it will fail every time an incomplete regex is used.
Maybe one of the other String Comparison would be better.
String comparisons are, by default, case and diacritic sensitive. You can modify an operator using the key characters c and d within square braces to specify case and diacritic insensitivity respectively, for example
firstName BEGINSWITH[cd] $FIRST_NAME.
The left-hand expression begins with the right-hand expression.
CONTAINS The left-hand expression contains the right-hand expression.
The left-hand expression ends with the right-hand expression.
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.
The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).