ios-Regular expression of __ regular expressions

Source: Internet
Author: User

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.


Related Article

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.