Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate/compare NSString with wildcards?

Hi I'm trying to evaluate an NSString to see if it fits a certain criteria, which contains wildcards in the form of one or more asterix characters.

Example:

NSString *filePath = @"file://Users/test/Desktop/file.txt";
NSString *matchCriteria = @"file://*/file.*";

I would like to see if filePath matches (fits?) matchCriteria, in this example it does. Does anybody know how I can go about doing this?

Many thanks!

like image 630
Lee82UK Avatar asked Jun 13 '26 14:06

Lee82UK


2 Answers

In addition to NSRegularExpression, you can also use NSPredicate.

NSString *filePath = @"file://Users/test/Desktop/file.txt";
NSString *matchCriteria = @"file://*/file.*";

NSPredicate *pred = [NSPredicate predicateWithFormat:@"self LIKE %@", matchCriteria];

BOOL filePathMatches = [pred evaluateWithObject:filePath];

The Predicate Programming Guide is a comprehensive document desribing how predicates work. They can be particularly useful if you have an array of items that you want to filter based on some criteria.

like image 83
dreamlax Avatar answered Jun 15 '26 03:06

dreamlax


NSString implements these methods:

@interface NSObject (NSComparisonMethods)
- (BOOL)isLike:(NSString *)object;
- (BOOL)isCaseInsensitiveLike:(NSString *)object;
@end

They are much faster than NSPredicate and NSRegularExpression.

like image 28
Elden Avatar answered Jun 15 '26 03:06

Elden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!