开发者

Remove area code from Telephonenumber

开发者 https://www.devze.com 2023-02-13 07:35 出处:网络
How to remove the coutrycode from telphonumber. the number could come in this format. 4770300000 004770300000

How to remove the coutrycode from telphonumber.

the number could come in this format.

4770300000
004770300000
+4770300000
4670300000

I开发者_高级运维 would like to remove countrycodes to be abile to match does number against.

070300000


The following should replace any valid country code (starting with "00" or "+") with a leading zero.

resultString = Regex.Replace(subjectString, @"^(00|\+)(1|2[078]|2[1234569][0-9]|3[0123469]|3[578][0-9]|4[013456789]|42[0-9]|5[09][0-9]|5[12345678]|6[0123456]|6[789][0-9]|7|8[0578][0-9]|8[123469]|9[0123458]|9[679][0-9])", "0");


Do you have a list of expected country codes? If so (assuming for this example that you're just looking for 47 and 46):

resultString = Regex.Replace(subjectString, @"(\+|\b00|\b)4[67]", "0");

would change

4770300000 004770300000 +4770300000 4670300000

into

070300000 070300000 070300000 070300000

However, it would also trigger on a phone number where the country code and area code have been omitted, if it happens to start with 47 or 46. To guard against this, you might want to add a lookahead assertion that checks that at least 8 (or whatever is reasonable) digits follow the presumed country code.

So

resultString = Regex.Replace(subjectString, @"(\+|\b00|\b)4[67](?=\d{8})", "0");

would change

4770300000 004770300000 +4770300000 460000

into

070300000 070300000 070300000 460000

If your input string is supposed to consist entirely of a phone number (as opposed to phone numbers embedded somewhere in a longer text), then you might want to use

resultString = Regex.Replace(subjectString, @"^(\+|00)4[67](?=\d{8})", "0");

instead. Thanks to Michael for the suggestion!


This is complicated. Both country codes and national numbers varies in length. In addition there are regional codes which some countries use and some don't. And then there's the optional leading '+', or '00'. Not to mention the emergency numbers.

But; Google to the rescue! This library solves your problem - in addition to a lot of other telephone number juggling. And it's ported to all major languages.

E.g. Here's how to strip away any country code from a number:

PhoneNumberUtil.GetInstance().Parse(phoneno, "").NationalNumber


If the phone number 070300000 has a fixed length you can get from the whole number only this length I mean f.e. 9 last numbers

0

精彩评论

暂无评论...
验证码 换一张
取 消