Reputation: 1476
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.
Upvotes: 3
Views: 457
Reputation: 626747
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).
Upvotes: 1