Regular Expressions for iOS

Source: Internet
Author: User

In the current stage of the development of iOS more and more, we in the development of the app will inevitably encounter the user login and registration to operate, but login registration if you want to do is the user-friendly verification, the current users of the login information to verify, If we meet the requirements we will put the user registration information into the database if information is not met we need to re-prompt user input, involving the verification that we can not do without the regular expression, let's learn how iOS operates regular expressions.

1, the regular expression of the syntax we do not detail here, if the unfamiliar to this can refer to the site: http://www.cnblogs.com/light169/archive/2006/10/18/532347.html

2, below we simply define an expression

// Regular expression Matching Yantai local telephone number        NSString * pattern=@ "^0535-\\d{6}$";          // string        to match NSString * str=@ "0535-6062799";

There are two main ways to deal with regular expressions in iOS, one in block form and one for non-block forms:

  Way One:

// define and initialize a Nsregularexpression object        Nsregularexpression * Reg=[[nsregularexpression alloc] initwithpattern:pattern options: Nsregularexpressiondotmatcheslineseparators Error:nil];

In the initialization method there is an options parameter that is an enumeration type, and we click the Go API as follows:

Let's simply translate

Nsregularexpressioncaseinsensitive//letter-case-insensitive mode

Nsregularexpressionallowcommentsandwhitespace//ignores whitespace in regular expressions and characters after #

Nsregularexpressionignoremetacharacters//handling regular expressions as a whole as strings

Nsregularexpressiondotmatcheslineseparators//Allow. Match any character, including line breaks

Nsregularexpressionanchorsmatchlines//Allow ^ and $ symbols to match the beginning and end of a line

Nsregularexpressionuseunixlineseparators//sets \ n is a unique line delimiter, otherwise all are valid.

Nsregularexpressionuseunicodewordboundaries//uses the Unicode tr#29 standard as the boundary of the word, otherwise the word boundaries of all traditional regular expressions are valid

// call the Matchesinstring method to return a matching array Nsarray * array= [reg MATCHESINSTRING:STR options:nsmatchingreportcompletion Range:nsmakerange (0, [str length ])];

The options are also available in the current method, and we click to view

Translate into Chinese

nsmatchingreportprogress = 1 << 0,//The block callback is called after finding the longest matching string

nsmatchingreportcompletion = 1 << 1,//find any one of the matching strings and call back once block

nsmatchinganchored = 1 << 2,//limit match from the start of the matching range

Nsmatchingwithtransparentbounds = 1 << 3,//Allow matching range beyond the set range

    nsmatchingwithoutanchoringbounds = 1 << 4  //suppress the ^ and $ auto-match lines or ends

// the array is loaded with Nstextcheckingresult, we print out the matching range within the object and intercept the string based on the range  for inch   Array) {            NSLog (@ "%@", Nsstringfromrange (Result.range));             * s=[str substringWithRange:result.range];            NSLog (@ "%@", s);        }

So that we can successfully say that the string match out.

Mode two:block mode parameter options are the same as the first of the above, using the following:

[Reg ENUMERATEMATCHESINSTRING:STR options:nsmatchingreportcompletion Range:nsmakerange (0, [str length]) usingblock:^ (Nstextcheckingresult *result, nsmatchingflags flags, BOOL *stop) {              NSLog (@ "%@  ", Nsstringfromrange (Result.range));               * s=[str substringWithRange:result.range];              NSLog (@ "%@", s);        }];

Way Three: we have now been able to match the simple string, but we sometimes need to split the string in the work, such as the string hello[Hello]world[Everybody good]good, we need to divide the string in Chinese, If it's an internship, we can use a third party to achieve a multiplier effect. below we used third-party Regexkitlite to achieve this function.

  1. We define regular expressions

// used to match Chinese  * pattern= @ "\\[[\\u4e00-\\u9fa5]+\\]"//            string         to match * str=@ "[haha]hello[hello]world[]good";

  2. Drag files into the project

3. Change the file to non-arc

4. Introduction of Auxiliary Library

5, the use is relatively simple, we need to introduce the first file, and then directly call the following methods can be

#import "RegexKitLite.h"  //used to get the split string[Str enumeratestringsseparatedbyregex:pattern usingblock:^ (Nsinteger capturecount, NSString *Const__unsafe_unretained *capturedstrings,ConstNsrange *capturedranges,volatileBOOL *Conststop) {NSLog (@"%@",*capturedstrings); }]; //used to get a matching string[Str enumeratestringsmatchedbyregex:pattern usingblock:^ (Nsinteger capturecount, NSString *Const__unsafe_unretained *capturedstrings,ConstNsrange *capturedranges,volatileBOOL *Conststop) {NSLog (@"%@",*capturedstrings); }];

Then we can happily use regular expression programming.

Jerry Education
Source:http://www.cnblogs.com/jerehedu/
This article is the copyright of Yantai Jerry Education Technology Co., Ltd. and the blog Park is shared, welcome reprint, but without the consent of the author must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Regular Expressions for 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.