开发者

Regular Expression for dialing prefix eg +44 etc

开发者 https://www.devze.com 2023-03-25 02:42 出处:网络
I realise making a regex for all internation numbers is futile. So as a compromise I need a regex that will check that a string starts with the international dialing code eg:

I realise making a regex for all internation numbers is futile. So as a compromise I need a regex that will check that a string starts with the international dialing code eg:

(+44) or (+33) etc.

I do开发者_JAVA技巧nt understand how to write regex's yet, so any help would be greatly appreciated.

P.s. It's for use in a c#.net project.

Thanks.


Try this

var regex=new Regex(@"^\(\+\d{1,4}\)");

I'm using the @ bit before the string so you don't need to double escape \

This does

^ Match Start of string

\( Match (

\+ Match +

\d{1,4} Match 1-4 digits

\) Match bracket

Also as you are using c# you may wish to consider using Expresso as this helps you build and test regular expressions targeted at the .Net Regular expression library and can even generate c# code for you to use them.


This is a complex matter, since the phone number needs not to be formatted, so it may have a digit right after the country code. Since these codes can have a varying length, you will need a list of country codes to check for. America and Russia have 1 and 7 respectively, most European countries and larger other countries have a two digit code, but there are also codes with 3 digits (not more, I believe). So you'll need a list of 1 and 2 digit codes at least, and can assume 3 digits if your phone number does not start with any code in that list.

I'd get this clear before you even start thinking whether to build this using regex or not. It may be easier in a simple piece of code.

0

精彩评论

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