Use and comparison of 3 regular expressions in iOS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.