Nsregularexpression Regular Expressions from iOS

Source: Internet
Author: User

Used to verify the mailbox, the phone number is usually used with third-party regular expressions or nspredicate (click here to view the previous article), in the late, Apple launched its own regular expression to provide developers call, very convenient, powerful.

You can see the official documentation, including how to write a regular expression for matching, and I won't go into more detail because I'm tired of looking at that bunch of symbols .... Had to turn to Google directly, the following only a few commonly used.

#define Kphoneregex  @ "\\d{3}-\\d{8}|\\d{3}-\\d{7}|\\d{4}-\\d{8}|\\d{4}-\\d{7}|1+[358]+\\d{9}|\\d{8}|\\d{7}" #define Kwebregex    @ "((http[s]{0,1}|ftp)://[a-za-z0-9\\.\\-]+\\. ( [A-za-z] {2,4}) (: \\d+)? (/[a-za-z0-9\\.\\[email protected]#$%^&*+?:_/=<>]*)?) | (www. [A-za-z0-9\\.\\-]+\\. ([a-za-z]{2,4}) (: \\d+)? (/[a-za-z0-9\\.\\[email protected]#$%^&*+?:_/=<>]*)?) " #define Kwebotherregex @ "http+:[^\\s]*" #define Kemailregex  @ "[A-z0-9a-z._%+-][email protected][a-za-z0-9.-]+\\ . [A-za-z] {2,4} "

/** 1. Returns a collection of all matching results (suitable for extracting all the data we want to match from a string) *-(Nsarray *) matchesinstring: (NSString *) string options: (nsmatchingoptions) op     tions Range: (nsrange) range; 2. Return the number of correct matches (by equals 0, to verify the mailbox, phone, etc. instead of nspredicate) *-(Nsuinteger) numberofmatchesinstring: (NSString *) string options: (NS     matchingoptions) Options Range: (nsrange) range; 3. Returns the result of the first match. Note that the matching results are saved in the Nstextcheckingresult type *-(Nstextcheckingresult *) firstmatchinstring: (NSString *) string options: (Nsma     tchingoptions) Options Range: (nsrange) range; 4. Return the first correctly matched result string Nsrange *-(Nsrange) rangeoffirstmatchinstring: (NSString *) string options: (nsmatchingoptions) Optio     NS Range: (nsrange) range; 5. Block method *-(void) enumeratematchesinstring: (NSString *) string options: (nsmatchingoptions) options range: (Nsrange) RA     Nge Usingblock: (void (^) (Nstextcheckingresult *result, nsmatchingflags flags, BOOL *stop)) block; *//** * Enum {nsregularexpressioncaseinsensitive = 1 << 0,//Case insensitive    Nsregularexpressionallowcommentsandwhitespace = 1 << 1,//Ignore spaces and #-NSREGULAREXPRESSIONIGNOREMETACHARACTE     rs = 1 << 2,//Integrated Nsregularexpressiondotmatcheslineseparators = 1 << 3,//matches any character, including line delimiter Nsregularexpressionanchorsmatchlines = 1 << 4,//allow ^ and $ at match start and end lines Nsregularexpressionuseunixlines  eparators = 1 << 5,//(Look for the whole word invalid) nsregularexpressionuseunicodewordboundaries = 1 << 6//     (Look for the whole word invalid)};     typedef Nsuinteger Nsregularexpressionoptions;  *///The following 2 enumerations do not seem to make sense, except in the Block method, in general, directly to 0 bar/** * Enum {nsmatchingreportprogress = 1 << 0, nsmatchingreportcompletion = 1 << 1, nsmatchinganchored = 1 << 2, Nsmatchi     Ngwithtransparentbounds = 1 << 3, nsmatchingwithoutanchoringbounds = 1 << 4};     typedef Nsuinteger Nsmatchingoptions; *//** This enumeration value only uses the * enum in the 5.block method{nsmatchingprogress = 1 << 0, nsmatchingcompleted = 1 << 1, nsmatching          Hitend = 1 << 2, nsmatchingrequiredend = 1 << 3, Nsmatchinginternalerror     = 1 << 4};     typedef Nsuinteger NSMATCHINGFLAGS;    *///test string, the inside of the phone number to parse out nsstring *urlstring = @ "haha haha oh s15279107723 here ah ah ah ah s15279107716";    Nserror *error = NULL; A regular expression (class method, similar to an instance method) is created based on the matching criteria nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:    Kphoneregex options:nsregularexpressioncaseinsensitive error:&error];        if (regex! = nil) {//3 .....                                                             Nstextcheckingresult *firstmatch = [Regex firstmatchinstring:urlstring        options:0 range:nsmakerange (0, [urlstring length])]; if (firstmatch) {Nsrange ResultRange = [Firstmatch RangeATINDEX:0];            Intercept data from urlstring nsstring *result = [URLString substringwithrange:resultrange];        NSLog (@ "result =%@", result);        }//2 .....                                                   Nsuinteger number = [Regex numberofmatchesinstring:urlstring options:0        Range:nsmakerange (0, [urlstring length])];        NSLog (@ "number =%ld", number); 5 .....        (The pit Daddy returns the first matching result) [Regex enumeratematchesinstring:urlstring options:0 range:nsmakerange (0, [urlstring length]) usingblock:^ ( Nstextcheckingresult *result, Nsmatchingflags flags, BOOL *stop) {NSLog (@ "---%@", nsstringfromrange ([result ran            GE]));                if (flags! = nsmatchinginternalerror) {Nsrange firsthalfrange = [result rangeatindex:0]; if (Firsthalfrange.length > 0) {nsstring *resultstring1 = [URLString Substringwithrange:firsthalfra                    Nge]; NSLog (@ "RESULT1 =%@ ", resultString1);        }} *stop = YES;    }];                                                        }//Replace the string you want to match nsstring *restring = [Regex stringbyreplacingmatchesinstring:urlstring options:0 range:nsmakerange (0, [UrlS    Tring length]) withtemplate:@ "(I am the replacement value)"];    NSLog (@ "restring =%@", restring);    There are 2 ways you can try it out//1.    Nsmutablearray *onearray = [self _matchlinkwithstr:urlstring withmatchstr:kphoneregex];    For (NSString *phone in Onearray) {NSLog (@ "phone =%@", phone); }

1.....-(Nsmutablearray *) _matchlinkwithstr: (NSString *) str withmatchstr: (NSString *) Matchregex;    {Nserror *error = NULL;                                                                         Nsregularexpression *reg = [Nsregularexpression Regularexpressionwithpattern:matchregex                                                                           Options:nsregularexpressioncaseinsensitive    error:&error];                                  Nsarray *match = [reg MATCHESINSTRING:STR options:nsmatchingreportcompletion        Range:nsmakerange (0, [str length])];    Nsmutablearray *rangearr = [Nsmutablearray array]; Get all Nsrange objects if (match.count! = 0) {for (Nstextcheckingresult *MATC in match) {Nsrang            E range = [MATC range];            Nsvalue *value = [Nsvalue valuewithrange:range];        [Rangearr Addobject:value]; }}//The value to be matched is taken out and stored in the array __block nsmutablearray *mularr = [nsmutablearRay Array]; [Rangearr enumerateobjectsusingblock:^ (id obj, Nsuinteger idx, BOOL *stop)        {Nsvalue *value = (nsvalue *) obj;        Nsrange range = [value rangevalue];    [Mularr addobject:[str Substringwithrange:range];    }]; return Mularr;}

Results


Nsregularexpression Regular Expressions from 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.