I'm using this code to bring my phone numbers in a consistent format.
Desired:
+(country code)phone number
Possible patterns:
01721234567
-> change to desired pattern
00491234567
-> change to desired pattern
+4912345678
-> do nothing, already desired pattern
This is what I use:
String number = allContactNumbers.get(i).get(j);
number = number.replaceAll("[^+0-9]", ""); // All weird characters such as /, -, ...
String country_code = getResources().getString(R.string.countrycode_de);
if (number.substring(0, 1).compareTo("0") == 0 && number.substring(1, 2).compareTo("0") != 0) {
number = "+" + country_code + number.substring(1); // e.g. 0172 12 34 567 -> + (country_code) 172 12 34 567
}
number = number.replaceAll("^[0]{1,4}", "+"); // e.g. 004912345678 -> +4912345678
For some reason I'm not happy with it though. I hope there is somebody to tell me, whether my code is written properly!
+
and all leading zeroes as step 1, and then just add the leading+
at the end? No country code begins with 0. \$\endgroup\$ – Edward Apr 3 '14 at 1:40