LeXeR
LeXeR

Reputation: 214

Regex to reject sequence of Digits

I need to validate phone number. Below is the code snippet

-(BOOL) validatePhone:(NSString*) phoneString
{

      NSString *regExPattern = @"^[6-9]\\d{9}$"; ORIGINAL
//    NSString *regExPattern = @"^[6-9](\\d)(?!\1+$)\\d*$";
      NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
      NSUInteger regExMatches = [regEx numberOfMatchesInString:phoneString options:0 range:NSMakeRange(0, [phoneString length])];
      NSLog(@"%lu", (unsigned long)regExMatches);
     if (regExMatches == 0) {
        return NO;
     }
     else
        return YES;
}

I want to reject phone number that is in sequnce example 9999999999, 6666677777

Upvotes: 1

Views: 296

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

It seems you want to disallow 5 and more identical consecutive digits.

Use

@"^[6-9](?!\\d*(\\d)\\1{4})\\d{9}$"

See the regex demo

Details

  • ^ - start of string
  • [6-9] - a digit from 6 to 9
  • (?!\d*(\d)\1{4}) - a negative lookahead that fails the match if, immediately to the right of the current location, there is
    • \d* - 0+ digits
    • (\d) - a digit captured into Group 1
    • \1{4} - the same digit as captured in Group 1 repeated four times
  • \d{9} - any 9 digits
  • $ - end of string (replace with \z to match the very end of string do disallow the match before the final LF symbol in the string).

Note that \d is Unicode aware in the ICU regex library, thus it might be safer to use [0-9] instead of \d.

Upvotes: 2

Related Questions