Please read the full post over at http://cocoawithlove.com.
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
criteria.
// 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
NSPredicate
(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
address?
NSString *emailRegEx =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";