There are three ways to implement regular expression matching in iOS. Now record them all here:
1. Using nspredicate (predicate) matching
For example, to match a valid mailbox:
NSString *email = @ "nijino_saki@163.com";
nsstring *regex = @ "[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[ a-za-z]{2,4} ";
nspredicate *predicate = [nspredicate predicatewithformat:@ "SELF matches%@", regex);
BOOL isValid = [predicate evaluatewithobject:email];
predicate matching is more flexible, but it requires knowledge of predicates.
2. Using rangeofstring:option: Direct lookup
NSString *searchtext = @ "//do no additional setup after loading the view, typically from a nib.";
Nsrange range = [SearchText rangeofstring:@] (?: [^,]) *\\. "Options:nsregularexpressionsearch];
if (range.location!= nsnotfound) {
NSLog (@ "%@", [SearchText Substringwithrange:range]);
}
The options set Nsregularexpressionsearch means that a regular expression match is used to return the position of the first matching result.
3. Using Regular Expression Classes
NSString *searchtext = @ "//do no additional setup after loading the view, typically from a nib.";
Nserror *error = NULL;
Nsregularexpression *regex = [Nsregularexpression regularexpressionwithpattern:@ "(?: [^,]) *\\." Options: Nsregularexpressioncaseinsensitive error:&error];
Nstextcheckingresult *result = [Regex firstmatchinstring:searchtext options:0 range:nsmakerange (0, [searchText length] )];
if (result) {
NSLog (@ "%@\n", [SearchText SubstringWithRange:result.range]);
}
Using the system's regular expression class (Nsregularexpression) returns multiple results that match.
Summary:
The first match needs to learn Nspredicate's writing, need to check Apple related technical documents; If you care only about the first matching result, the second match is simpler; If you need to match multiple results and match them multiple times, the third way is more efficient.