3

I have seperate regex validations for my requirement but struggling to combine them in one. I am validation mobile numbers with country code or starting with 00 and also if they contain extension number(2-5 digits) seperated by #

Following is the example of valid Number :

+919986040933
00919986040933
+919986040933#12
+919986040933#123
+919986040933#1234
+919986040933#12345

I have following regex to validate the above:

var phoneRegexWithPlus = "^((\\+)|(00))[0-9]{10,14}$";
var phoneRegexWithZero = "^((\\+)|(00))[0-9]{9,12}$";
var phoneRegexExtension = "^[0-9]{2,5}$";

Currently i am checking whether number contains #,if yes then split it and match number and extension part seperately where extension is comething after hash.

My problem is now that i have to create one regex combining the above three,can anyone help me with that as m not good in regex. Thanks in advance.

Pratswinz
  • 1,476
  • 11
  • 24

1 Answers1

1

I suggest this expression:

^\+?(?:00)?\d{12}(?:#\d{2,5})?$

See the regex demo

Expression explanation:

  • ^ - start of string
  • \+? - an optional plus (as ? matches the + one or zero times)
  • (?:00)? - an optional 00
  • \d{12} - Exactly 12 digit string
  • (?:#\d{2,5})? - an optional (again, ? matches one or zero times) sequence of:
    • # - a literal hash symbol
    • \d{2,5} - 2 to 5 digits (your phoneRegexExtension)
  • $ - end of string.

The phoneRegexWithPlus and phoneRegexWithZero are covered with the first obligatory part \+?(?:00)?\d{12} that matches 12 to 14 digits with an optional plus symbol at the start.

NOTE: The regex is adjusted to the sample input you provided. If it is different, please adjust the limiting quantifiers {12} (that can be replaced with, say, {9,14} to match 9 to 14 occurrences of the quantified pattern).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • be aware that your regex will catch: +00111111111111 , which is not one of the required cases – Jumpa Jul 08 '16 at 14:13
  • 1
    @Jumpa: Look at OP regexps, [they match the same](https://regex101.com/r/bB7cT7/1) and have no restrictions as for what the order of digits is or what digits can or cannot appear in the number. All I did was *merging* the patterns into a single one. – Wiktor Stribiżew Jul 08 '16 at 14:14