0
votes

I haven't used regular expressions yet in objective-c. What I'm trying to do right now is evaluate a string to see if it contains a 4 or 5 character repeating pattern - any pattern, it doesn't matter. For instance, a string like @"testA54RqA54Rq" would return a true value from the regex, while a string like @"testA54Rq" would not. Right now I'm just generating all possible 4 and 5 character substrings and matching them to each other, but obviously this is extremely inefficient. Where can I find some resources about how to start using regular expressions in objective C? If anyone's been in this situation before a small example would be nice.

-EDIT-

I would also like to have somthing like @"testQWEr30BKRe40" return true (pattern of 4 letters followed by 2 numbers). I'm not sure if this is possible.

2
They work the same as in other languagues. You use NSPredicate or (iOS >= 4.0, OS X >= 10.7) NSRegularExpression. See the Predicate Programming Guide for details. - jscs

2 Answers

1
votes

For exact patterns you will be able to do such validation with regex (.{4,5})\\1

If you want to do category pattern, such as 4 letters followed by 2 numbers, then you have to:

  1. replace all letters with one constant letter (for example replace [a-zA-Z] with X)
  2. replace all numbers with one constant number (for example replace \\d with 0)
  3. validate such modified input with the same regex as shown above
2
votes

You probably want to look at:

https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

The actual regex I believe would just be: (\\w{4,5})\\1


NSString *regexStr = @"(\\w{4,5})\\1"; 
NSError *error = nil; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error]; 
if ((regex==nil) && (error!=nil)) {
  warn( @"Regex failed for: %@, error was: %@", string, error); 
} else {

}