How to match either 0 or + followed by 1 to 3 digit number at the beginning but not both?

Viewed 117

I have following regular expression to check mobile number

^(0\d{10,15})$|(?!\1)(\+\d{1,3}\d{10,15})$

the string should match either 0 at the beginning followed by 10 to 15 digits

or (but not both)

the string with a + at the beginning with 1 to 3 digit country code followed by 10 to 15 digits

the first condition is matched but number with +[country-code] does not

3 Answers

You need to use

^(?:0|\+[1-9]\d{0,2})\d{10,15}$

Details:

  • ^ - start of string
  • (?:0|\+[1-9]\d{0,2}) - 0 or a +, a non-zero digit ([1-9]) and then zero, one or two digits (\d{0,2})
  • \d{10,15} - 10 to 15 digits
  • $ - end of string.

See the regex demo.

Another variant could be

^(?:0\d{10,15}|\+\d{11,18})$
  • ^ Start of string
  • (?: Non capture group
    • 0\d{10,15} Match 0 and 10-15 digits
    • | Or
    • \+\d{11,18} Match + and 11-18 digits
  • ) Close non capture group
  • $ End of string

Regex demo

let regex = /^(?:0|\+\d{1,3} ?)\d{10,15}$/;

console.log(regex.test("01234567890"));
console.log(regex.test("0 1234567890"));
console.log(regex.test("+91 1234567898765"));
console.log(regex.test("+91123456789876567576654765675576"));

Related