iOS implementation of simple book account recognition method (regular expression)

Source: Internet
Author: User

Through the simple book iOS client login, we will see please enter the phone number or email login, but we randomly input 1234567, it will pop up the phone format is not correct, also will recognize our mailbox format, then we in the project how to achieve this judgment?


0e471361-060c-4d93-913f-73622f89bc60.png

This is the regular expression that we are going to talk about today.

Introduction to Regular expressions

There are many ways to use regular expressions, according to our needs, we are to determine whether the input is legitimate, or to find the specified content, or to capture multiple input content, you can choose a different method, today we mainly say, to determine whether the input is legitimate, using predicates to create a regular expression, if useful later, Write one more article.

predicate (nspredicate)

nspredicate" mean #ffffff? Nspredicate is predicate logic. is similar to the SQL statement for a database, and is filtered from the data heap by criteria. predicate, which specifies the condition of the filter, preserves the eligible objects, generally uses predicates to filter the specified elements in the array, defines the predicate object, contains the filter elements in the predicate object, and uses the predicate condition filter to get the results we want. All in all, Cocoa provides a class nspredicate class that is primarily used to specify the condition of the filter, which can accurately describe the required conditions, filter each object through predicates, and determine if the condition matches. predicates represent functions that calculate true or false values. The following code example, first we create a class named student, and then set the id,name,height for him. We then introduce this class to assign him the following code:

    NSMutableArray *array=[NSMutableArray arrayWithCapacity: 5];    Student *student1=[[Student alloc] init];    [student1 setPid: 1];    [student1 setName: @"xiaoming"];    [student1 setHeight: 168];    [array addObject: student1];    Student *student2=[[Student alloc] init];    [student2 setPid: 2];    [student2 setName: @"dahuang"];    [student2 setHeight: 178];    [array addObject: student2];    Student *student3=[[Student alloc] init];    [student3 setPid: 3];    [student3 setName: @"erhuang"];    [student3 setHeight: 188];    [array addObject: student3];

In the above code, we created a mutable array, and three pupils (-_-, do not spit out slots I give them the name, too lazy to think ...). Below we are going to create our predicate, we want to filter out an ID greater than 1, and raise less than 180 of elementary school students, what should be done.

 NSPredicate *pre = [NSPredicate predicateWithFormat:                        @" pid>1 and height<188.0"];     int i=0;    for(i=0;i<[array count];i++){        Student *stu=[array objectAtIndex: i];        //遍历数组,输出符合谓词条件的Student 的name。        if ([pre evaluateWithObject: stu]) {            NSLog(@"11--%@",[stu name]);        }    }

Predicates can also help us make some filtering of columns, as follows:

  //快速筛选数组内容   以及占位符的使用    NSPredicate *pre2 = [NSPredicate predicateWithFormat:@"pid>%d",1];    NSMutableArray *arrayPre2=[array filteredArrayUsingPredicate: pre2];    NSLog(@"%@",[[arrayPre2 objectAtIndex: 0] name]);

Processing of strings

 //name以x开头的    NSPredicate  *predicate3 = [NSPredicate predicateWithFormat:@"name BEGINSWITH ‘x‘"]; //name以g结尾的    NSPredicate  *predicate4 = [NSPredicate predicateWithFormat:@"name ENDSWITH ‘g‘"];  //name中包含字符a的    NSPredicate  *predicate5 = [NSPredicate predicateWithFormat:@"name CONTAINS ‘a‘"];   //like 匹配任意多个字符    //name中只要有r字符就满足条件    NSPredicate  *predicate6 = www.90168.org[NSPredicate predicateWithFormat:@"name like ‘*r*‘"];  //?代表一个字符,下面的查询条件是:name中第二个字符是r的    NSPredicate  *predicate7 = [NSPredicate predicateWithFormat:@"name like ‘*?r*‘"];

The use of predicates first here, is not the same as the database used to feel the same, the following talk about the time to come, how do we do the predicate and the regular expression combination of the corresponding judgment?

Using regular expressions to realize judgment

First we create a UI that contains a Uitextfield input box and a Submit button, which we judge when we click on the button. We create a class that writes out a way to judge the phone number and the mailbox

+ (BOOL)GS_isMobileNumber:(NSString *)mobileNum;+ (BOOL)GS_isEmailQualified:(NSString *)emailStr;

Then implement the detection method

+ (BOOL) Gs_ismobilenumber: (NSString *) mobilenum{/** * Mobile phone number * Move: 134[0-8],135,136,137,138,139,150,151,157,158,1 59,182,187,188 * Unicom: 130,131,132,152,155,156,185,186 * Telecom: 133,1349,153,180,189 *///NSString * MOBILE =    @ "^1 (3[0-9]|5[0-35-9]|8[025-9]) \\d{8}$"; /** * Mobile: China Mobile * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188 * *//NSString * CM = @ "^1 (34[0-8]| ( 3[5-9]|5[017-9]|8[278] \\d) \\d{7}$ "; Chinese Mobile phonenum/** * Unicom: China Unicom * 130,131,132,152,155,156,185,186 *///NSString * C U = @ "^1 (3[0-2]|5[256]|8[56]) \\d{8}$"; Chinese Unicom phonenum/** * China Telecom: Chinese Telecom * 133,1349,153,180,189 *//NSString * CT = @ "^1 (( 33|53|8[09]) [0-9]|349] \\d{7}$ "; China Telecom Phonenum/** * The following 4 www.90168.org predicate can tell which carrier the number are from.     *///Nspredicate *regextestmobile = [Nspredicate predicatewithformat:@ "Self MATCHES%@", MOBILE];    Nspredicate *REGEXTESTCM = [Nspredicate predicatewithformat:@ "Self MATCHES%@", CM];    Nspredicate *REGEXTESTCU = [Nspredicate predicatewithformat:@ "Self MATCHES%@", CU];    Nspredicate *REGEXTESTCT = [Nspredicate predicatewithformat:@ "Self MATCHES%@", CT];    Only Check if the string is a valid telephone number, ignoring the carrier info. NSString *ismobileregex = @ "^ (((13[0-9]{1}) | ( 15[0-9]{1}) | (17[0-9]{1}) | (18[0,5-9]{1})) +\\D{8}) $ ";//NSString *ismobileregex = @" ^ ((\\+86) | ( \ \ (\\+86\\))? ((13[0-9]{1}) | (15[0-9]{1}) | (17[0-9]{1}) | (18[0,5-9]{1}))    +\\D{8}) $ ";    Nspredicate *mobileregex = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Ismobileregex];    if ([mobileregex evaluatewithobject:mobilenum] = = yes) {return yes;    }else{return NO; }}
//检测是否为邮箱+ (BOOL)GS_isEmailQualified:(NSString *)emailStr{    NSString *pattern = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];    NSArray *results = [regex matchesInString:emailStr options:0 range:NSMakeRange(0, emailStr.length)];    return results.count > 0;}

Then we call the created method to detect if the phone number

   if ([GSRegularExpression GS_isMobileNumber:_textfiled.text]) {        NSLog(@"输入的是正常的手机号码");    }else{        NSLog(@"输入的不是正常的手机号码");    }

According to the printed results, we are correct, so that we implement the regular expression of the mobile phone number and the mailbox decision (this is the way the mailbox is called).

Postscript

Regular expressions to judge some of the results, is more commonly used, such as ID card, license plate, model, IP address, input is the full number and so on. Using him we can achieve some seemingly more complex effect, now we have realized the simple book login to the mobile phone number and mailbox recognition function, I hope to help you. There is something wrong in the text, please be positive to point out.

Supplementary Supplement 1:

For example, we are given a regular to determine the password

+(BOOL)judgePassWordLegal:(NSString *)pass{    BOOL result ;    // 判断长度大于8位后再接着判断是否同时包含数字和字符    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];    result = [pred evaluateWithObject:pass];    NSLog(@"%hhd",result);    return result;}

How do we understand the above? First the opening tag "^" ends with the mark "$", [0-9a-za-z]{6,20} indicates that the content contains numbers and letters and limits his number of digits, (?! [0-9]+$] This form is negative pre-check, the specific format meaning, here put on an online link is not written, the use of regular expressions .

Supplement 2:

About the comments inside the login question here to add: The basic process is only for reference, there are improper welcome to point out.

    • Authorized--After authorization, the request interface--already bound--returns the login information

    • Unauthorized--After authorization, the request interface is not bound---(the phone number is already registered)--(OpenID and UserID or phone number binding, then return login information)

    • Not authorized--after authorization, the request interface--not bound---not registered--create account, bind id--> return login information

iOS implementation of simple book account recognition method (regular expression)

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.