1
\$\begingroup\$

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.

asked Feb 17, 2017 at 5:44
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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.

answered Aug 13, 2017 at 7:06
\$\endgroup\$
0
\$\begingroup\$

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");
}
answered Jun 13, 2017 at 18:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.