35

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?

1
  • 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. Commented Aug 14, 2013 at 16:42

4 Answers 4

59

I've used NSPredicate for that purpose:

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

if ([myTest evaluateWithObject: testString]){
//Matches
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, can I use default regular expression syntax for someRegexp?
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 that email regex is inadequate. Email addresses may contain unicode and top level domains are not 2 to 4 characters long.
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
28

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.

Comments

3

NSRegularExpression is another option:

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

Comments

2

Use the -isMatchedByRegex: method.

if([someString isMatchedByRegex:@"^[0-9a-fA-F]+:"] == YES) { NSLog(@"Matched!\n"); }

4 Comments

NB that is not part of cocoa. very simple answer here .. stackoverflow.com/questions/4353834/…
Well, @Vladimir's answer seems more simple to me.
== YES is redundant
Not a great idea to use this library just to perform a very simple action included in Cocoa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.