I have a list for validated mobile numbers that I have to display in the same way:
The desired format is:+34 666 111 222
String telefonos =
"666444555,
666-444-555,
666 44 45 55,
666-44-45-55,
+34666555444,
0034666555444";
Pattern pattern = Pattern.compile(""); // aqui es donde me clavo.
Matcher matcher = pattern.matcher(telefonos);
while (matcher.find())
System.out.println(matcher.group());
Expected output:
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 444 555
+34 666 555 444
+34 666 555 444
Try the following regular expression:
If you plan to use this expression frequently, it is recommended to use a constant to avoid recompiling the expression every time, ie:
Departure:
The same as in the other question, I recommend you use
libphonenumber
( Google's library to validate phone numbers). It has many advantages compared to doing your own implementation, for example that you don't have to maintain it yourself and that it gives you the number in international format, no matter how the user enters it.An example of how it is used is:
Now there are a number of methods but the most important would be:
Here you will always be able to have the international format you want:
Of course, I always recommend that you ask the question of whether or not the number is valid before asking about its international format.
To see a demo you can go here .