dotnetnoob
dotnetnoob

Reputation: 11360

How to combine these regex requirements?

I'm using an Asp.Net RegularExpressionValidator to validate phone numbers.

The check is quite basic - a number can be 10 or 11 characters in length, all numeric and starting 01 or 02.

Here's the regex:

^0[12]\d{8,9}$

However, I've recently started working with a 3rd party, who enforce stricter rules. In my opinon it's a bad idea - partly because they don't even publish these rules, and they are subject to change and therefore maintenance across all their partners. However...

I now need to incorporate their additions into my regex, but I'm not sure where to start.

They currently do this using 2 separate regexes in an OR, however I'd like to do this in 1 if possible.

The additional syntax should ensure that for 10 digit phone numbers also adhere to these additional rules - here's their 10 digit syntax.

"^01(204|208|254|276|297|298|363|364|384|386|404|420|460|461|480|488|524|527|562|566|606|629|635|647|659|695|726|744|750|768|827|837|884|900|905|935|946|949|963|995)[0-9]{5}$ 

Any ideas as to how to achieve this?

Upvotes: 0

Views: 88

Answers (2)

HamZa
HamZa

Reputation: 14931

Disclaimer: This answer is based on the logic followed by this answer to demonstrate the "virtual" requirements (which we should drop anyways).

Let me explain what is going on:
^0[12]\d{8,9}$ What's going on here ?

  • ^ : match begin of line
  • 0 : match 0
  • [12] : match 1 or 2
  • \d{8,9} : match a digit 8 or 9 times
  • $ : match end of line

^01(204|20...3|995)[0-9]{5}$ What does this big regex do ?

  • ^ : match begin of line
  • 01 : match 01.
  • (204|20...3|995) : match certain 3 digit combination
  • [0-9]{5} : match a digit 5 times
  • $ : match end of line

Well, what if we merged these two in an OR statement ?

^
   (?:
       01(204|20...3|995)[0-9]{5}
   )
   |
   (?:
        0[12]\d{8,9}
    )
$

I'll show you why it doesn't make sense.
How many digits does 0[12]\d{8,9} match ? 10 or 11 right ?
Now how many digits does the other regex match ?

01(204|20...3|995)[0-9]{5}
^^ ^-----\/-----^ ^--\/--^
2    +    3      +    5     =   10

Now if we compare the 2 regexes. It's clear that ^0[12]\d{8,9}$ will match all the digits that are valid for the other regex. So why in the world would you combine these 2 ?

To make the problem simpler, say you have regex1: abc, regex2: [a-z]+. What you want is like abc|[a-z]+, but that doesn't make sense since [a-z]+ will match abc, so we can get ride of abc.

On a side note, \d does match more than you think in some languages. Your final regex should be ^0[12][0-9]{8,9}$.

Upvotes: 2

Firas Dib
Firas Dib

Reputation: 2621

You could merge them with an OR in the regex itself:

^(?:01(204|208|254|276|297|298|363|364|384|386|404|420|460|461|480|488|524|527|562|566|606|629|635|647|659|695|726|744|750|768|827|837|884|900|905|935|946|949|963|995)\d{5}|0[12]\d{9})$

Edited 11 digit regex.

Upvotes: 1

Related Questions