1

I have a mobile number field and I want to check if it has Any digit repeated 9 times, including zero and if Any phone number or mobile number only composed of two different digits.

Is there any Regex or something to do this?

In Portugal phone numbers starts with 2######## and mobile with 91/92/93/96 and both have 9 digits.

Mara Pimentel
  • 317
  • 1
  • 8
  • 14
  • For testing if a phone number has any number repeated 9 times you can use the following: `([0-9])\1{8}`. If you don't want to include the 2 from the from of the string you can just append it to the start of this regular expression. `2([0-9])\1{8}` – d0nut Dec 15 '15 at 15:08

2 Answers2

3

This Regex will only match 9 following numbers starting with a 2 or 91,92,93,96

^(?:2\d|9[1236])[0-9]{7}$

^ = start of string

(?:2\d|9[1236]) = 2 + any number OR 9 followd by 1,2,3 or 6

[0-9]{7} = 7 numbers

$ = end of string

domacs
  • 104
  • 6
3

Try this regex:

^(?:(?:(2)([013-9])|(9)([1236]))(?!(?:\1|\2){7})(?!(?:\3|\4){7})\d{7}|(?=2{2,7}([^2])(?!(?:2|\5)+\b))22\d{7})\b

Regex live here.

Explaining:

^                              # from start
(?:                            # look at (?:...) as subsets
  (?:                          # 
    (2)([013-9])|(9)([1236])   # store possible digits in groups \1 \2 \3 \4
  )                            #
  (?!(?:\1|\2){7})             # in front cannot repeat only \1 \2
  (?!(?:\3|\4){7})             # neither only \3 \4
  \d{7}                        # plus seven digits to complete nine
|                              # or
  (?=                          # to avoid number repetitions:
    2{2,7}([^2])               # in front should be possible to match
                               # the number 2 from 2 to seven times 
                               # and another digit stored in \5
    (?!(?:2|\5)+\b)            # but not only them,
                               # so, should match another digit 
                                   # (not two or the \5) till the boundary
  )                            #
  22\d{7}                      # then, it refers to 22 and 7 digits = nine
)\b                            # confirm it don't overflows nine digits

Hope it helps.

  • I think that is what I want! Is there a possibility to add the regex that accepts only numbers and no characters? i'm using this one but what I want to know if I can add it to the one you wrote. I'm using this one ^[0-9]+$ – Mara Pimentel Dec 15 '15 at 15:58
  • You can change the last `\b` in my regex to `$`... and replace yours by mine... and do not need to care about not digits.. as my regex allows only numbers :) –  Dec 15 '15 at 16:10
  • @MaraPimentel. Glad to help :) –  Dec 15 '15 at 17:26