Match regular expression to string (file name)

I am trying to distinguish 2 files (in NSString format). As far as I know, this can be done by comparing and matching the regex. The format of the two jpg files that I have is:

butter.jpg

oil-1.jpg

My question is: what regular expression can I write to fit the two lines above? I searched and found an example of an expression, but I'm not sure how it reads and thinks it is 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 = @"[az]+-[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)

At the moment it works, but I want to exclude any chances that it might not be, any inputs?

+6
source share
2 answers
 NSString *regEx = @"[az]+-[0-9]+.+jpg"; 

will fail for butter.jpg , as it must have one - and at least by number.

 NSString *regEx = @"[az]+(-[0-9]+){0,1}.jpg"; 

and if you do

 NSString *regEx = @"([az])+(?:-([0-9])+){0,1}.jpg"; 

You can access information that you probably would like to receive later, as capture groups.

(...) | Capturing brackets. The input range that matched the subexpression in parentheses is available after the match.

and if you do not need capture groups

 NSString *regEx = @"(?:[az])+(?:-[0-9]+){0,1}.jpg"; 

(?: ...) | Lacking parentheses. Groups the included template, but does not capture the corresponding text. Somewhat more efficient than capturing parentheses.

+4
source

You can match an alphabetic character (in any language) with \p{L} . You can match a digit with \d . You need to avoid . because in regular expression . means "any character".

Regular expression analysis is expensive, so you only need to do this once.

 BOOL stringMatchesMyPattern(NSString *string) { static dispatch_once_t once; static NSRegularExpression *re; dispatch_once(&once, ^{ re = [NSRegularExpression regularExpressionWithPattern: @"^\\p{L}+-\\d+\\.jpg$" options:0 error:NULL]; } return nil != [re firstMatchInString:string options:0 range:NSMakeRange(0, string.length)]; } 
+2
source

All Articles