I'm trying to format some phone numbers with regexp. The phone numbers i have stored are of diffrent length and all phone numbers have their country codes. Lets say a number looks like this: 00460708186681. I want that one to be formatted as: +46 (0)708-18 66 81. The first three groups are easy:
/00([\d]{2})([\d]{1})([\d]{3})/
Because the beginning of the number will always be the same. It's the last part where i dont know the length of the remaining chars (and i want them to be divided into groups of two).
Start with the following regex as your base:
00(\d{2})(\d)(\d{3})(\d{2})
Now add another pair (\d{2})?
(note the '?') for every pair it's possible to have. So if the maximum number of pairs is 3, you do the following:
00(\d{2})(\d)(\d{3})(\d{2})(\d{2})?(\d{2})?
It's not pretty, but you need to do it that way in order to get them grouped correctly. Or you could simply do:
00(\d{2})(\d)(\d{3})((?:\d{2}){2,4}) // In this case it's 2 to 4 pairs of digits on the end.
To match the string, then you can manually add spaces in the last group which will contain all the digits after your initial formatting.