2

I am new to java regex. I have to validate the telephone phone numbers using java regex. I have tried some combinations, this being the best result so far:

^\s*(?:\+?(011))?[-. (]*?(1|32)?[-. (]*(703|701|21)?[-. )]*(\d{3})?[-. ]*(\d{4})?\s*$ 

Acceptable inputs:

 1.  ####
 2.  (###)###-#### 
 3.  ###-####
 4. +#(###)###-####
 5.  #####.#####

Unacceptable inputs: 

 1. ###
 2. #/###/###/####
 3. nr ###-###-####
 4. ##########
 5. (###) ###-####

where # highlights numbers/digits

Thanks in advance.

shd293
  • 97
  • 1
  • 8
  • 1
    Possible duplicate of [Regular expression to match standard 10 digit phone number](http://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number) – Atul Mar 11 '17 at 03:02

1 Answers1

3

You have basically two possibilities. Either you can find a factorized regular expression that fits your need but is likely to be unreadable and unmaintainable, or you can opt for a longer regex that expresses exactly each of your cases.

The second is incredibly easier to write and to maintain. Let's take your two first acceptable inputs. They can be illustrated in the following way:

enter image description here

The regex is written using a switch cases approach: (\d{5}|\(\d{3}\)\d{3}-\d{4}), where the character pipe (|) acts as a separator between your cases. Thus, you can specify the exact syntax of your required input.

The illustration has been generated on https://www.debuggex.com/, a tool I highly recommend when dealing with regular expressions.

As your question mentioned Java, it's then trivial to check a regex in java, thanks to the method matches of any instance of String:

boolean matched = "(703)111-2121".matches("(\\d{5}|\\(\\d{3}\\)\\d{3}-\\d{4})")

As you can read, you have to think to espace the backslash in the code!

Jämes
  • 6,945
  • 4
  • 40
  • 56