34

since regular exressions are not supported in Cocoa I find RegexKitLite very usefull. But all examples extract matching strings.

I just want to test if a string matches a regular expression and get a Yes or No.

How can I do that?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
  • 2
    Regular expressions 'not supported in Cocoa'? `NSRegularExpression` has been part of the framework since the release of iOS 4.0, almost a year before this question was asked, and there have apparently been methods that made use of regexes since before `NSRegularExpression` was introduced, as touched upon in, for instance, Vaz's answer. – Mark Amery Aug 14 '13 at 16:42

4 Answers4

59

I've used NSPredicate for that purpose:

NSString *someRegexp = ...; 
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", someRegexp]; 

if ([myTest evaluateWithObject: testString]){
//Matches
}
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • thanks, can I use default regular expression syntax for someRegexp? – DarkLeafyGreen Apr 25 '11 at 09:31
  • 2
    I think yes, e.g. I used that for simple email validation: NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; – Vladimir Apr 25 '11 at 09:33
  • 3
    @Vladimir that email regex is inadequate. Email addresses may contain unicode and top level domains are not 2 to 4 characters long. – Winny Apr 16 '14 at 03:57
  • 3
    It served my purpose and I had no complaints from users :) But you can easily replace it with better one, as it is not part of this question anyway – Vladimir Apr 16 '14 at 07:14
27

Another way to do this, which is a bit simpler than using NSPredicate, is an almost undocumented option to NSString's -rangeOfString:options: method:

NSRange range = [string rangeOfString:@"^\\w+$" options:NSRegularExpressionSearch];
BOOL matches = range.location != NSNotFound;

I say "almost undocumented", because the method itself doesn't list the option as available, but if you happen upon the documentation for the Search and Comparison operators and find NSRegularExpressionSearch you'll see that it's a valid option for the -rangeOfString... methods since OS X 10.7 and iOS 3.2.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
Vaz
  • 678
  • 6
  • 16
2

Use the -isMatchedByRegex: method.

if([someString isMatchedByRegex:@"^[0-9a-fA-F]+:"] == YES) { NSLog(@"Matched!\n"); }
johne
  • 6,760
  • 2
  • 24
  • 25