Phone number regex for multiple patterns in Java
I need help writing a regex for a phone number pattern that allows the following formats for a phone number
1)###-###-#### or 2)#-###-##开发者_Go百科#-#### or 3)###-#### or 4)########## or 5)#######
I am well aware, that you are able to find regex patterns on the internet, but I havent been able to find one that will pass for all these patterns.
I am using Java
You could use the | (or) operator and multiple patterns.
For example:
(\d{7})|(\d{10)|
...
try ^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$
Here is an online regular expression evaluator, you can test your patterns against this regex and/or any other.
public int Phone(String num)
{
try
{
String expression = "^(?=.{7,32}$)(\\(?\\+?[0-9]*\\)?)?[0-9_\\- \\(\\)]*((\\s?x\\s?|ext\\s?|extension\\s?)\\d{1,5}){0,1}$";
CharSequence inputStr = num;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
int x=0,y=0;
char[] value=num.toCharArray();
for(int i=0;i<value.length;i++)
{
if(value[i]=='(')
x++;
if(value[i]==')'&&((value[i+1]>=48&&value[i+1]<=57)||value[i+1]=='-'))
y++;
}
if(matcher.matches()&&x==y)
return 1; //valid number
else
return 0; //invalid number
}
catch(Exception ex){return 0;}
}
}
This regex will match all local numbers and international numbers.
String reg= "([\\+(]?(\\d){2,}[)]?[- \\.]?(\\d){2,}[- \\.]?(\\d){2,}[- \\.]?(\\d){2,}[- \\.]?(\\d){2,})|([\\+(]?(\\d){2,}[)]?[- \\.]?(\\d){2,}[- \\.]?(\\d){2,}[- \\.]?(\\d){2,})|([\\+(]?(\\d){2,}[)]?[- \\.]?(\\d){2,}[- \\.]?(\\d){2,})";
1 ###-###-####
2 #-###-###-####
3 ##########
4 +### ##-###-####
5 ###.###.####
6 ### ### ####
7 (###)### ####
All of the above formats would work.
Try this
^\d?-?(\d{3})?-?\d{3}-?\d{4}$
Try this regular expression:
@"^(((\d-)?\d{3}-)?(\d{3}-\d{4})|\d{7}|\d{10})$"
This covers the five scenarios you've described; Alternatively, if you can also accept the following scenarios:
6)###-#######
or
7)#-###-#######
or
8)#-##########
Then this shorter variant will work also:
@"^(((\d-?)?\d{3}-?)?(\d{3}-?\d{4}))$"
This allows extensions, UK international formats, and checks min length 7 characters
^(?=.{7,32}$)(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*((\s?x\s?|ext\s?|extension\s?)\d{1,5}){0,1}$
Don't require the user to enter the number in any particular format.
Let them enter it however they want.
Strip any country code and store it for later use, likewise any extension number data if present.
Strip any spaces and punctuation.
Check that the remaining digits are potentially valid by looking at the leading digits and the number length.
Store the number in your database in international format with country code, without spaces or punctuation.
Show the number back to the user in a standardised format (either national format or international format with country code) with added spaces and punctuation for readability.
精彩评论