Before I introduced the use of regular expressions in iOS in blog post (portals), I found that there were three ways to match regular expressions in iOS. Now put them all on the record here:
1. Using nspredicate (predicate) matching
For example, to match a valid mailbox:
NSString *email = @ "[email protected]163@"[A-z0-9a-z._%+-][email protected][ A-za-z0-9.-]+\\. [A-za-z] {2,4} " *predicate = [nspredicate predicatewithformat:@ "selfMATCHES%@"= [ predicate evaluatewithobject:email];
predicate matching is more flexible, but requires knowledge of predicates.
2. Using rangeofstring:option: Direct lookup
@" additional setup after loading the view, typically from a nib. " = [SearchText rangeofstring:@ "(?: [^,]) *\\. " if (range.location! = nsnotfound) {NSLog (@ "%@" , [SearchText Substringwithrange:range]); }
The set nsregularexpressionsearch in options means that a regular expression match is used to return the position of the first matching result.
3. Using the Regular expression class
NSString *searchtext =@"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:0Range: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 consult Apple related technical documents; If you only care about the results of the first match, the second match is more concise; If you need to match multiple results and match them multiple times, the third way is more efficient.
Use and comparison of 3 regular expressions in iOS