Regular Expression For Password in iPhone?

一曲冷凌霜 提交于 2019-12-21 02:45:13

问题


I am pretty much weak in creating Regular Expression. So I am here.

I need a regular expression satisfying the following.

  1. Atleast one numeric value and Atleast one alphabet should be present for the password
  2. Minimum 6 Maximum 32 characters should be allowed.

回答1:


 -(BOOL) isPasswordValid:(NSString *)pwd {
     if ( [pwd length]<6 || [pwd length]>32 ) return NO;  // too long or too short
     NSRange rang;
     rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
     if ( !rang.length ) return NO;  // no letter
     rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
     if ( !rang.length )  return NO;  // no number;
     return YES;
 }

This is clearly not a regex, but imo regex is overkill for this.




回答2:


Try this:

^(?=.*\d)(?=.*[A-Za-z]).{6,32}$



回答3:


Without using any third party libraries like Regexkit you can check for your requirements like so:

    if ([[password rangeOfCharacterFromSet: [ NSCharacterSet alphanumericCharacterSet]] &&
         [password rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @"0123456789"]] && 
        (6 < [password length]) && [password length] < 32)) {
              NSLog(@"acceptable password");
        }



回答4:


Here you can find a usefull regexp cheatsheet wich also provide some examples. One of these is really similar to your needs (the 6th in the "Sample pattern box) :)




回答5:


The following should meet the minimum/max characters, at least 1 alpha and 1 numeric character requirements:

^(?=.{6,32}$)(?=.*\d)(?=.*[a-zA-Z]).*$


来源:https://stackoverflow.com/questions/5514311/regular-expression-for-password-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!