NSPredicate with regex capture always gets 0 results - ios

Hi to all overflowers,
I'm scratching my head around putting a regular expression inside an NSPredicate.
I would like to move all our thumbnails from Documents directory into Caches directory and catch em'all I've created this regex: _thumb(#[2-3]x)?\.jpg.
Here on regex101.com you can see the above regex working with this test data:
grwior_thumb.jpg <- match
grwior.jpg
vuoetrjrt_thumb#2x.jpg <- match
vuoetrjrt.jpg
hafiruwhf_thumb.jpg <- match
hafiruwhf_thumb#2x.jpg <- match
hafiruwhf_thumb#3x.jpg <- match
hafiruwhf.jpg
But when I put it in the code it's not matching anything:
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
// Find and move thumbs to the caches folder
NSArray<NSString *> *mediaFilesArray = [fileManager contentsOfDirectoryAtPath:documentsPath error:&error];
NSString *regex = #"_thumb(#[2-3]x)?\\.jpg";
NSPredicate *thumbPredicate = [NSPredicate predicateWithFormat: #"SELF ENDSWITH %#", regex];
NSArray<NSString *> *thumbFileArray = [mediaFilesArray filteredArrayUsingPredicate:thumbPredicate];
thumbFileArray has always 0 elements...
What am I doing wrong?

Use MATCHES rather than ENDSWITH, as ENDSWITH does not treat the expression as a regular expression, but make sure you match all the chars from the start of the string, too, as MATCHES requires a full string match, so you need to somehow match the chars before the _.
Use
NSString *regex = #".*_thumb(#[23]x)?\\.jpg";
And then
[NSPredicate predicateWithFormat: #"SELF MATCHES %#", regex]
The .* will match any 0+ chars other than line break chars, as many as possible.
Note that if you just want to match either 2 or 3, you might as well write [23], no need for a - range operator here.
You may also replace (#[23]x)? with (?:#[23]x)?, i.e. change the capturing group to a non-capturing, since you do not seem to need the submatch to be accessible later. If you do, keep the optional capturing group.

The problem is with ENDSWITH.
ENDSWITH
The left-hand expression ends with the right-hand expression.
MATCHES
The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3
What you need is
NSString *regex = #".+_thumb(#[2-3]x)?\\.jpg";
NSPredicate *thumbPredicate = [NSPredicate predicateWithFormat: #"SELF MATCHES %#", regex];

Related

Validate a string using regex

I want to validate a string to check if it is alphanumeric and contains "-" and "." with the alphanumeric characters. So I have done something like this to form the regex pattern
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[a-zA-Z0-9\\.\\-]"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSPredicate *regexTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
BOOL valid = [regexTest evaluateWithObject:URL_Query];
App crashes stating that the regex pattern cannot be formed . Can anyone give me a quickfix to what am i doing wrong? Thanks in advance.
You must pass a variable of type NSString to the NSPredicate SELF MATCHES:
NSString * URL_Query = #"PAS.S.1-23-";
NSString * regex = #"[a-zA-Z0-9.-]+";
NSPredicate *regexTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
BOOL valid = [regexTest evaluateWithObject:URL_Query];
See the Objective C demo
Note that you need no anchors with the SELF MATCHES (the regex is anchored by default) and you need to add + to match one or more allows symbols, or * to match 0+ (to also allow an empty string).
You do not need to escape the hyphen at the start/end of the character class, and the dot inside a character class is treated as a literal dot char.
Also, since both the lower- and uppercase ASCII letter ranges are present in the pattern, you need not pass any case insensitive flags to the regex.

Is there a way to check if a string contains a Unicode letter?

In Cocoa, regular expressions are presumably following the ICU Unicode rules for character matching and the ICU standard includes character properties such as \p{L} for matching all kinds of Unicode letters. However
NSString* str = #"A";
NSPredicate* pred = [NSPredicate predicateWithFormat:#"SELF MATCHES '\\p{L}'"];
NSLog(#"%d", [pred evaluateWithObject:str]);
doesn't seem to compile:
Can't do regex matching, reason: Can't open pattern U_REGEX_BAD_INTERVAL (string A, pattern p{L}, case 0, canon 0)
If character properties are not supported (are they?), how else could I check if a string contains a Unicode letter in my iOS app?
The main point here is that MATCHES requires a full string match, and also, \ backslash passed to the regex engine should be a literal backslash.
The regex can thus be
(?s).*\p{L}.*
Which means:
(?s) - enable DOTALL mode
.* - match 0 or more any characters
\p{L} - match a Unicode letter
.* - match zero or more characters.
In iOS, just double the backslashes:
NSPredicate * predicat = [NSPredicate predicateWithFormat:#"SELF MATCHES '(?s).*\\p{L}.*'"];
See IDEONE demo
If the backslashes inside the NSPrediciate are treated specifically, use:
NSPredicate * predicat = [NSPredicate predicateWithFormat:#"SELF MATCHES '(?s).*\\\\p{L}.*'"];

NSPredicate - Return inexact matches

In my app I allow users to search for vehicles by make/model using a textfield keyword search. Here is my predicate:
if (self.keywordSearch.text.length > 0) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fields.make CONTAINS[cd] %# OR fields.model CONTAINS[cd] %#", self.keywordSearch.text, self.keywordSearch.text];
self.vehicleArray = [[self.vehicleArray filteredArrayUsingPredicate:predicate] mutableCopy];
}
The problem is that if the Vehicle make/model is 'Ford F-150' and the user searches F150, or F 150, the vehicle isn't included in the results. It only returns if they search F-150 or f-150.
Is there a way to make sure these inexact matches are returning?
I suggest using regular expressions for this. You can either use a regular expression literal inside the NSPredicate format (described here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html ) or you can iterate the array manually and use an NSRegularExpression for comparing the strings.

add componentsseparatedbystring into a predicate with core data

i have a String stored in an Entity (core data) i want to use an NSFetchedResultsController to get data.
string format: abc,ba,x,s,d. this is an array of IDs saved as string.
i want to get only entities that contains at least an IDs in that string.
the problem is if i use CONTAIN in the predicate and search for "a" i will get a wrong result.
could you please tel me if it's possible to add something like "componentsseparatedbystring" in a predicate so i can iterate and use "in"in the result or if there's an other solution, thanks.
You can use the "MATCHES" operator in a predicate, which does a
regular expression match:
NSString *searchID = #"a";
NSString *pattern = [NSString stringWithFormat:#"(^|.*,)%#(,.*|$)",
[NSRegularExpression escapedPatternForString:searchID]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ID MATCHES %#", pattern];
The pattern (^|.*,)TERM(,.*|$) searches for TERM which is preceded
by either the start of the string or a comma, and followed by the
end of the string or another comma.
First convert your array of ID's into an NSArray:
NSArray *arrayOfIds = [stringOfIds componentsSeparatedByString:#","];
Then use an IN predicate on your fetch:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ID IN %#", arrayOfIds];
this assumes your database column is called "ID", and your comma-separated string of ID's is stringOfIds.
finally i will use a dirty solution: we have 4 possibilities:
string format= a
string format= a,..
string format= ..,a
string format= ..,a,..
so the predicate could be:
[NSPredicate predicateWithFormat:#"(ID LIKE %# OR
ID CONTAINS %# OR
ID CONTAINS %# OR
ID ENDSWITH %#)",
searchedID,
[NSString stringWithFormat:#"%#,", searchedID],
[NSString stringWithFormat:#",%#", searchedID],
[NSString stringWithFormat:#",%#,", searchedID]]
but this is a dirty solution, i really want something cleaner.

NSPredicate to match unescaped apostrophes

I'd like to check an NSString (json) if there are any unescaped apostrophes, but the NSPredicate won't find it, even if the regex is correct.
Here's my code:
NSString* regx = #"[^\\\\]'";
NSPredicate* p = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",regx];
if([p evaluateWithObject:json]){
//gotit
...
I know that there are some apostrophes that are not escaped, but NSPredicate just doesn't find it.
Any idea how to solve this problem?
Also if I look at the json I see the apostrophes as \u0027.
"SELF MATCHES …" tries to match the entire string, therefore you have to use the regex
NSString* regx = #".*[^\\\\]'.*";
Alternatively:
NSString* regx = #"[^\\\\]'";
NSRange r = [json rangeOfString:regx options:NSRegularExpressionSearch];
if (r.location != NSNotfound) {
…
}
But the question remains why this is necessary. NSJSONSerialization should handle
all escaping and quoting correctly.
This is the regex which works for me:
.*[^\\\\]\\\\u0027.*

Resources