Java Number Format formatPhone(String phoneNumber, String formattingPattern, String countryCode)

Here you can find the source of formatPhone(String phoneNumber, String formattingPattern, String countryCode)

Description

Format phone numbers (to international phone number format - eg +41 41 882 32 21)

License

Open Source License

Parameter

Parameter Description
phoneNumber Unformatted/Formatted phone number with optional country code. Brackets for area code and special characters (like -) for local number is supported.
formattingPattern Defines the format of the phone number (eg. ## ### ## ## for 41 841 44 44). The formattingPattern must not include the country code.
countryCode Country code (+41, 0041, 41)

Return

If the phone number does not match the formatting pattern the original phone number will be returned. Otherwise the formatted phone number will be returned.

Declaration

public static String formatPhone(String phoneNumber, String formattingPattern, String countryCode) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010-2015 BSI Business Systems Integration AG.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from   w  w  w  .j ava2 s .co  m*/
 *     BSI Business Systems Integration AG - initial API and implementation
 ******************************************************************************/

public class Main {
    /**
     * Format phone numbers (to international phone number format - eg +41 41 882 32 21)
     *
     * @since
     * @param phoneNumber
     *          Unformatted/Formatted phone number with optional country code. Brackets for area code and special
     *          characters (like -) for local number is supported.
     * @param formattingPattern
     *          Defines the format of the phone number (eg. ## ### ## ## for 41 841 44 44). The formattingPattern must not
     *          include the country code.
     * @param countryCode
     *          Country code (+41, 0041, 41)
     * @return If the phone number does not match the formatting pattern the original phone number will be returned.
     *         Otherwise the formatted phone number will be returned.
     */
    public static String formatPhone(String phoneNumber, String formattingPattern, String countryCode) {
        if (phoneNumber == null) {
            return null;
        }
        if (formattingPattern == null) {
            return phoneNumber;
        }
        if (countryCode == null) {
            return phoneNumber;
        }

        // declare local variables
        int numberPattern = "#".charAt(0);
        String formattedPhoneNumber = "";
        String normalizedNumber;
        boolean patternIsMatching = false;
        boolean hasCountryCode = false;

        // calc. pattern lenght without spaces, etc.
        int patternLengh = formattingPattern.replaceAll("[^#]", "").length();

        /* normalize phone number */
        normalizedNumber = phoneNumber.replaceAll("[^(0-9|\\+)]|(\\(|\\))", "");

        // check for country code
        hasCountryCode = normalizedNumber.matches("(^(0{2})[0-9]*)|(^\\+{1}[0-9]*)");

        /* normalize country code (no spaces; no leading +/00 */
        countryCode = countryCode.replaceAll("[^0-9]", "");
        countryCode = countryCode.replaceAll("^(0{0,2})", "");

        // phone number has country code
        if (hasCountryCode) {
            // remove country code
            normalizedNumber = normalizedNumber.replaceAll("^(0{0,2})", "");
            normalizedNumber = normalizedNumber.replaceAll("^(\\+)", "");
            normalizedNumber = normalizedNumber.replaceAll("^" + countryCode, "");
        }

        // add leading zeros of the area code. is required for a propper matching
        // with the pattern
        if (patternLengh == normalizedNumber.length() + 1 && !normalizedNumber.startsWith("0")) {
            normalizedNumber = "0" + normalizedNumber;
            patternIsMatching = true;

            // normalized phone number is matching pattern
        } else if (patternLengh == normalizedNumber.length()) {
            patternIsMatching = true;
        }

        // format the normalized phone number
        if (patternIsMatching) {
            int count = 0;
            for (int i = 0; i < formattingPattern.length(); i++) {
                if (formattingPattern.charAt(i) == numberPattern) {
                    if (count < normalizedNumber.length()) {
                        formattedPhoneNumber += normalizedNumber.charAt(count);
                        count++;
                    }
                } else {
                    formattedPhoneNumber += formattingPattern.charAt(i);
                }
            }

            // remove zeros of the area code
            formattedPhoneNumber = formattedPhoneNumber.replaceAll("^[0]+", "");
            // add country code
            formattedPhoneNumber = "+" + countryCode + " " + formattedPhoneNumber;

        } else {
            // do nothing
            formattedPhoneNumber = phoneNumber;
        }

        return formattedPhoneNumber;
    }

    public static int length(CharSequence s) {
        if (s == null) {
            return 0;
        } else {
            return s.length();
        }
    }
}

Related

  1. formatPaddedNumber(long number, int numericPadding)
  2. formatPartialName(String name, int numberOfCharacters)
  3. formatPattern(String number, String pattern)
  4. formatPct(final Number amount)
  5. formatPercentage(Number numerator, Number denominator)
  6. formatPhoneNo(String country, String area, String number, String inline)
  7. formatPhoneNumber(String number)
  8. formatPhoneNumber(String phoneNumber)
  9. formatPrintIntegerToString(long number, boolean printCommasP, boolean printSignP, int radix, int mincol, char padchar, char commachar, int commainterval)