16

In the following code I am trying to get the output to be the different formatting of phone numbers and if it is either valid or not. I figured everything out but the Java Regular Expression code on line 11 the string pattern.

 import java.util.regex.*;

  public class MatchPhoneNumbers {
   public static void main(String[] args) {           
     String[] testStrings = {               
               /* Following are valid phone number examples */             
              "(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
              /* Following are invalid phone numbers */ 
              "(1234567890)","123)4567890", "12345678901", "(1)234567890",
              "(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};

             // TODO: Modify the following line. Use your regular expression here
              String pattern = "^/d(?:-/d{3}){3}/d$";    
             // current pattern recognizes any string of digits           
             // Apply regular expression to each test string           
             for(String inputString : testStrings) {
                System.out.print(inputString + ": "); 
                if (inputString.matches(pattern)) {     
                    System.out.println("Valid"); 
                } else {     
                    System.out.println("Invalid"); 
                }
             }
      }
  }
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Ducky
  • 181
  • 1
  • 3
  • 8
  • Possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Naman Feb 08 '17 at 04:20
  • 3
    are those 4 the only valid format? other than that considered invalid? just create regex for each 4 of them then – Baby Feb 08 '17 at 04:23
  • Note that the atom that matches a digit is `\d`, not `/d`, and you'll need to write it as `\\d` if you're in a `String` literal. – Dawood ibn Kareem Feb 08 '17 at 04:25
  • is "123456-7890" considered valid? – Patrick Parker Feb 08 '17 at 04:51
  • What country is this for? If you need to validate international phone numbers then you will need to determine the country code first and then apply several regexes for each country. Bear in mind that in several countries mobile numbers have a different length from land lines, and phone number layouts (where the spaces/dashes go) has changed over the years. I.e. my old (many years ago) phone number in Spain was `+34 91 411-6280` but nowadays it is also written as `+34 914 116 280`. Good luck. – Jim Garrison Feb 08 '17 at 06:11

5 Answers5

23

Basically, you need to take 3 or 4 different patterns and combine them with "|":

String pattern = "\\d{10}|(?:\\d{3}-){2}\\d{4}|\\(\\d{3}\\)\\d{3}-?\\d{4}";
  • \d{10} matches 1234567890
  • (?:\d{3}-){2}\d{4} matches 123-456-7890
  • \(\d{3}\)\d{3}-?\d{4} matches (123)456-7890 or (123)4567890
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
  • 2
    how can we get if number contains country code like : **+91-123-456-7890** OR **+911-22228888** how can we define patterns to find out these types of phone no's. – UltimateDevil Jun 26 '17 at 07:01
  • @VikasKumarTiwari you seem to be confused about how to use this site. If you are 100% certain that the numbers will only appear in those two patterns, then start a new question, stating as such. Otherwise, you should read the answers for [this more general question](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Patrick Parker Jun 27 '17 at 09:17
  • Thanks @Patrick Parker I have done. your answer helped me a lot. I have tried some efforts and i have done – UltimateDevil Jun 27 '17 at 11:57
7

Considering these facts about phone number format:-

  1. Country Code prefix starts with ‘+’ and has 1 to 3 digits
  2. Last part of the number, also known as subscriber number is 4 digits in all of the numbers
  3. Most of the countries have 10 digits phone number after excluding country code. A general observation is that all countries phone number falls somewhere between 8 to 11 digits after excluding country code.
String allCountryRegex = "^(\\+\\d{1,3}( )?)?((\\(\\d{1,3}\\))|\\d{1,3})[- .]?\\d{3,4}[- .]?\\d{4}$";

Let's break the regex and understand,

  • ^ start of expression
  • (\\+\\d{1,3}( )?)? is optional match of country code between 1 to 3 digits prefixed with '+' symbol, followed by space or no space.
  • ((\\(\\d{1,3}\\))|\\d{1,3} is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.
  • \\d{3,4}[- .]? is mandatory group of 3 or 4 digits followed by hyphen, space or no space
  • \\d{4} is mandatory group of last 4 digits
  • $ end of expression

This regex pattern matches most of the countries phone number format including these:-

        String Afghanistan      = "+93 30 539-0605";
        String Australia        = "+61 2 1255-3456";
        String China            = "+86 (20) 1255-3456";
        String Germany          = "+49 351 125-3456";
        String India            = "+91 9876543210";
        String Indonesia        = "+62 21 6539-0605";
        String Iran             = "+98 (515) 539-0605";
        String Italy            = "+39 06 5398-0605";
        String NewZealand       = "+64 3 539-0605";
        String Philippines      = "+63 35 539-0605";
        String Singapore        = "+65 6396 0605";
        String Thailand         = "+66 2 123 4567";
        String UK               = "+44 141 222-3344";
        String USA              = "+1 (212) 555-3456";
        String Vietnam          = "+84 35 539-0605";

Source:https://codingnconcepts.com/java/java-regex-for-phone-number/

Ashish Lahoti
  • 648
  • 6
  • 8
5

international phone number regex

String str=  "^\\s?((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?\\s?";


 if (Pattern.compile(str).matcher(" +33 - 123 456 789 ").matches()) {
        System.out.println("yes");
    } else {
        System.out.println("no");
    } 
Anurag Gupta
  • 59
  • 1
  • 2
3

The regex that you need is:

String regEx = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";

Regex explanation:

^\\(? - May start with an option "("

(\\d{3}) - Followed by 3 digits

\\)? - May have an optional ")"

[- ]? - May have an optional "-" after the first 3 digits or after optional ) character

(\\d{3}) - Followed by 3 digits.

[- ]? - May have another optional "-" after numeric digits

(\\d{4})$ - ends with four digits

Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
1

Create a non-capturing group for three digits in parenthesis or three digits (with an optional dash). Then you need three digits (with another optional dash), followed by four digits. Like, (?:\\(\\d{3}\\)|\\d{3}[-]*)\\d{3}[-]*\\d{4}. And you might use a Pattern. All together like,

String[] testStrings = {
        /* Following are valid phone number examples */         
        "(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
        /* Following are invalid phone numbers */
        "(1234567890)","123)4567890", "12345678901", "(1)234567890",
        "(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};

Pattern p = Pattern.compile("(?:\\(\\d{3}\\)|\\d{3}[-]*)\\d{3}[-]*\\d{4}");
for (String str : testStrings) {
    if (p.matcher(str).matches()) {
        System.out.printf("%s is valid%n", str);
    } else {
        System.out.printf("%s is not valid%n", str);    
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249