如何从长描述字段中提取联系电话

本文关键字:提取 联系电话 字段 描述 | 更新日期: 2023-09-27 18:07:50

这是我的长输入字符串,在这个字符串之间包含联系电话,如下所示:

sgsdgsdgs (123) 456-7890SDFSDFSDFS +91 (123) 456-7890

现在我想提取所有的输入数字,如:

123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890

我想把所有这些数字存储在数组中

这是我尝试过的,但只有2个数字:

string pattern = @"^'s*(?:'+?('d{1,3}))?[-. (]*('d{3})[-. )]*('d{3})[-. ]*('d{4})(?: *x('d+))?'s*$";
 Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
 var a = txt.Split();
 List < string > list = new List < string > ();
 foreach(var item in a) {
     if (reg.IsMatch(item)) {
         list.Add(item);
     }
 }
有谁能帮我一下吗?

如何从长描述字段中提取联系电话

不要使用Split

通过匹配并得到它们的Groups[0].Value,应该是这样的:

foreach (var m in MyRegex.Match(myInput).Matches)
    Console.WriteLine(m.Groups[0].Value);

在regexhero上测试:

  1. Regex: 's*(?:'+?('d{1,3}))?[-. (]*('d{3})[-. )]*('d{3})[-. ]*('d{4})(?:[ ]*x('d+))?'s*
  2. 输入:sgsdgsdgs 123-456-7890 sdgsdgs (123) 456-7890 sdgsdgsdg 123 456 7890 sdgsdgsdg 123.456.7890 sdfsdfsdfs +91 (123) 456-7890
  3. 输出:5 matches

    • 123-456-7890
    • (123) 456-7890
    • 123 456 7890
    • 123.456.7890
    • +91 (123) 456-7890

edit: regexhero不喜欢最后一组的空格,只好用[ ]代替

尝试在字符串上直接使用正则表达式,如:

using System.IO;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        Regex regex = new Regex(@"'s*(?:'+?('d{1,3}))?[-. (]*('d{3})[-. )]*('d{3})[-. ]*('d{4})(?: *x('d+))?'s*");
        Match match = regex.Match("sgsdgsdgs 123-456-7890 sdgsdgs (123) 456-7890 sdgsdgsdg 123 456 7890 sdgsdgsdg 123.456.7890 sdfsdfsdfs +91 (123) 456-7890");
        List < string > list = new List < string > ();
        while (match.Success)
        {
            list.Add(match.Value);
            match = match.NextMatch();
        }
        list.ForEach(Console.WriteLine);
    }
}

您得到两个数字,因为split()默认使用空格作为分隔符。

试试下面测试过的代码。

static void Main(string[] args)        
        {
            string txt = "sgsdgsdgs 123-456-7890 sdgsdgs (123) 456-7890 sdgsdgsdg 123 456 7890 sdgsdgsdg 123.456.7890 sdfsdfsdfs +91 (123) 456-7890";
            Regex regex = new Regex(@"'s*(?:'+?('d{1,3}))?[-. (]*('d{3})[-. )]*('d{3})[-. ]*('d{4})(?: *x('d+))?'s*");
            List<string> list = new List<string>();
            foreach (var item in regex.Matches(txt))
            {
                list.Add(item.ToString());
                Console.WriteLine(item);
            }
        Console.ReadLine();
    }