Search code examples
objective-cregexcore-datanspredicate

CoreData NSPredicate MATCHES regex


I have a CoreData table with a field holding a string of a series of numbers separated by commas. I want to be able to run a fetch with a predicate that will match against a given specific number.

For example if fieldName = "12,52,66,89,2,8"

And I want to search for 2, then it should match the second to last number in the string and include that record in the results.

Using the regular expression: ^2|,2,|,2 I have found it working satisfactorily for my test cases, testing it using this site for example: https://www.regexpal.com/

However, when I pass this into an NSPredicate for a NSFetchRequest, I can't get it to match

NSNumber *val = @2;
NSString *regex = [NSString stringWithFormat:@"^%@|,%@,|,%@", val, val, val];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"fieldName MATCHES %@", regex];

Replacing the MATCHES with a CONTAINS val makes it work, but of course it will also incorrectly match any occurrence of the digits.

I suspect I am missing something stupid about formatting for CoreData (or regex), but I've tried many variations, and I'm hoping a kind soul reading this will put me out of my misery :)


Solution

  • Disclaimer: I haven't used Objective C. This answer is based on my regex knowledge and some documentation.

    MATCHES 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).

    That sounds like how Java uses the method "matches" in which case "^2|,2,|,2" can never match the entire string. This differs from regexpal which will always search the text. The regex you would need is more like

    .*\b2\b.*
    

    (the ^$ are assumed in Java). Another option is to split the string.