MSISDN country code detection

2.4k views Asked by At

How can I detect the country code from the following MSISDN?

Cyprus (+357XXXXXXXX) -- 11 digits

Finland (+358XXXXXXXXXX) -- 13 digits

Serbia (+381XXXXXXX) -- 10 digits

Different countries have different number of digits in their country code and also in their MSISDN, so, there is no way to match the country code alone from the entire number.

So, how can I get the country code from a specific MSISDN?

1

There are 1 answers

4
Ivaylo Slavov On

If the data is present in a fixed format: {country_code} {space} {phone_digits}, you could easily use string operations (regex, splitting and so on) to get the country code part. To determine which country the code represents, you should match it against a list of known country codes - either store these in your database or use a web service for the validation.

A possible approach is to get from a database the country codes, and compare manually where you find a match - in case the format is not consistent. This could be error prone, as country codes may also differ in length and you could match the wrong one. A somewhat acceptable approach, if there is no other choice, is to first match the longest, and then the shorter codes - yet there is no guarantee for invalid matches. To completely avoid the issue, consider the next suggestion:

If you have control over how the phone numbers are persisted (in your database or whatever storage you use), I'd advice you to store the country code in a separate field. For SQL database, this will mean you have a column for the country code and another for the phone number. You can then easily extract the country code with absolute certainty and process it in whatever way you like.


As seen from comments, the format in question is something you expect your api clients to provide. If that is the case, you should attempt to enforce some constraints to the format - make the client pass the country code as a separate parameter, or use a separator symbol that would be appropriate. If so, you will end up parsing the code and determining the country. It will be up to the client to conform to the desired format.