I'm trying to differentiate between 2 files (in NSString format). As far as I know, this can be done by comparing and matching a regular expression. The format of the 2 jpg files which I have are:
butter.jpg
butter-1.jpg
My question is what regular expression can I write to match the 2 strings above? I've search and found an example expression, but I'm not sure how is it read and think it's wrong.
Here is my code:
NSString *exampleFileName = [NSString stringWithFormat:@"butter-1.jpg"];
NSString *regEx = @".*l{2,}.*";
NSPredicate *regExTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
if ([regExTest evaluateWithObject:exampleFileName] == YES) {
NSLog(@"Match!");
} else {
NSLog(@"No match!");
}
EDIT:
I tried using the following:
NSString *regEx = @"[a-z]+-[0-9]+.+jpg";
to try to match:
NSString *exampleFileName = [NSString stringWithFormat:@"abcdefg-112323.jpg"];
Tested with:
abc-11.jpg (Match)
abcsdas-.jpg (No Match)
abcdefg11. (No Match)
abcdefg-3123.jpg (Match)
As of now it works, but I want to eliminate any chances that it might not, any inputs?
NSString *regEx = @"[a-z]+-[0-9]+.+jpg";
will fail for butter.jpg
, as it needs to have one -
and at least on number.
NSString *regEx = @"[a-z]+(-[0-9]+){0,1}.jpg";
and if you do
NSString *regEx = @"([a-z])+(?:-([0-9])+){0,1}.jpg";
You can access the informations you probably would like to have later as capture groups.
(...) |Capturing parentheses. Range of input that matched the parenthesized subexpression is available after the match.
and if you dont need capture groups
NSString *regEx = @"(?:[a-z])+(?:-[0-9]+){0,1}.jpg";
(?:...)| Non-capturing parentheses. Groups the included pattern, but does not provide capturing of matching text. Somewhat more efficient than capturing parentheses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With