asp.net 获取C# 提取字符串里的电话手机号码
以下是提取电话的代码,兼容11位手机号、3位或4位区号+8位电话号、400电话的两种写法(400-ddd-dddd、400ddddddd)。如有其他格式的电话号码需要提取,请自行添加正则规则。/// <summary>
/// 提取字符串中的电话号
/// * 兼容11位手机号、3位或4位区号+8位电话号、400电话的两种写法(400-ddd-dddd、400ddddddd)
/// </summary>
/// <param name="input">输入的字符串</param>
/// <returns></returns>
public static List<string> GetTelephoneList(string input)
{
//集合存放提取出来的电话号码
List<string> list = new List<string>();
/*
* 正则表达式提取
* 分为五种格式,能兼容11位手机号、3位或4位区号-7位或8位电话号、400电话的两种写法(400-ddd-dddd、400ddddddd)
*/
Regex regex = new Regex(@"(1[3|4|5|6|7|8|9]\d{9})|(0\d{2,3}-\d{7,8})|(400-\d{3}-\d{4})|(400\d{7})");
// @"^(1)[3-9]\d{9}$"
//Match集合,匹配成功的字符串集合
MatchCollection collection = regex.Matches(input);
//遍历Match集合,取出值
string telephone;
foreach (Match item in collection)
{
foreach (Group group in item.Groups)
{
telephone = group.Value.Trim();
//偶尔会出现重复提取,所以加了去重判断
if (!string.IsNullOrEmpty(telephone) && !list.Contains(telephone))
{
list.Add(telephone);
}
}
}
return list;
}