Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a regular expression with a string (file name)

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?

like image 881
Dawson Avatar asked Dec 19 '12 08:12

Dawson


Video Answer


1 Answers

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.

like image 179
vikingosegundo Avatar answered Nov 05 '22 15:11

vikingosegundo