# Checking that a 6-digit number is not repeated and not in sequence

Following is the objective C code snippet to check that the 6-digit number is not repeated and not in sequence/reverse-sequence. I have just printed the proper messages in NSLog that user should be allowed or not:

 NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?!(\\d)\\1+$|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\\d$)\\d{6}$" options:NSRegularExpressionCaseInsensitive error:&error];

NSRange matchRange = [regex rangeOfFirstMatchInString:text options:NSMatchingReportCompletion range:NSMakeRange(0, text.length)];

BOOL didValidate = NO;
if(matchRange.location != NSNotFound){
didValidate = YES;
}
if(didValidate){
NSLog(@"Allowed");
}else{
NSLog(@"Not Allowed");
}


I just want to know if this regex has an effect on performance, and if yes, then what should be optimal solution for it. It would be great if anyone can provide their inputs for the same.

I would write a separate function for validating a string (so that it has a name and you can talk about it).

Then, I would not use regular expressions for it but just simple code:

• The length must be 6.
• Only digits are allowed.
• For each pair of adjacent digits, their difference must be at least 2.

That should be much easier to understand than your regular expression.

There are few things that I think can be improved.

First of all you are not bothering to check for ERROR, if any like:

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?!(\\d)\\1+$|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\\d$)\\d{6}$" options:NSRegularExpressionCaseInsensitive error:&error];
if(error){
NSLog(@"Error occurred in regex: %@", error.debugDescription);
}


Second thing is you can improve if-else logic without having separate variable as:

if(matchRange.location != NSNotFound){
NSLog(@"Allowed");
}else{
NSLog(@"Not Allowed");
}