Regex solution for Objective-C

7 Solutions Collect From Internet About “Regex solution for Objective-C”

NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '.*@.*\..*'"];
BOOL result = [predicate evaluateWithObject:@""];

According to the Predicate guide:

The left hand expression equals the right hand expression using
a regex-style comparison according to
ICU v3 (for more details see the ICU
User Guide for Regular Expressions).

There’s even an example written by Apple that can be found in the guide.

Instead of SELF you could also use a key path. (And possibly some other literals too.)

Please read the full post over at

In Cocoa, NSPredicate works in much
the same way as the “WHERE” clause of
SQL. The main reason that NSPredicate
is being brought to the iPhone is that
NSPredicate fulfils the same role in
Core Data that “WHERE” clauses fulfil
in SQL — to allow the persistent store
to fetch objects that satisfy specific

// given an NSDictionary created used the above method named "row"...
NSPredicate *johnSmithPredicate =
    [NSPredicate predicateWithFormat:@"firstname = 'John' AND lastname = 'Smith'"];
BOOL rowMatchesPredicate = [johnSmithPredicate evaluateWithObject:row];

Verifying an email address

The “LIKE” comparison operator in
(NSLikePredicateOperatorType) is
commonly used as a convenient means of
testing if an NSString matches a
Regular Expression. It’s advantage
over full libraries with greater
options and replacement capability is
that it is already in Cocoa — no
libraries, no linkage, no hassle.

You can do a simple test:

NSPredicate *regExPredicate =
    [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regularExpressionString];
BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:myString];

The only question that remains is:
what is a regular expression that can
be used to verify that an NSString
contains a syntactically valid email

NSString *emailRegEx =
  • Desktop: RegExKit like Mr. Vile mentioned.
  • iPhone: RegExKitLite works great.

Have a try with CSRegex:

It is meant to be a quick and simple regex class that can be dropped into any Cocoa project with a minimum of fuss. It consists of only two files, and no external dependencies.

Another option is the libregex wrapper in the Google Toolbox for Mac: