mdaza mdaza - 3 months ago 10
Java Question

how to make this regular excepression work with java - android?

How to use this with

String.matches(...........)


^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$


It would match the following examples and much more:

18005551234
1 800 555 1234
+1 800 555-1234

+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
800 555 1234x5678
8005551234 x5678
1 800 555-1234
1----800----555-1234

Answer

First, you need to escape the first + in your pattern.

Then, make delimiters optional and allow more than one in consequence to match all variants like 1 (800) 555-1234, (800) 555-1234, and 18005551234.

The regex would be:

^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: ?x(\d+))?\s*$

Demo: https://regex101.com/r/pV4hL9/1

Finally, in Java, escape backslashes with backslashes: https://ideone.com/L6bNA9

Comments