从句子中正确提取字符串

Correctly extracting strings from a sentence

这个问题我已经研究了一段时间了,希望我能找到一些解决办法。

我有一个句子,其中包含我想提取的关键信息。

提取这些字符串后,我会将它们保存为一个数组,然后将这些字符串与我的数据库中存在的内容进行比较。

我遇到的问题是成功提取字符串。

比如我有这句话:

These are a list of automobiles along with their production dates: AC 3000ME (1979-1984), AC Shelby-Cobra (1961-2004), AC Frua (1965-1973).

我想提取:3000MEShelby-CobraFrua

下面是代码:

 public string CarModelMethod()
        {
            string sentence = "These are a list of automobiles along with their production dates: AC 3000ME (1979-1984), AC Shelby-Cobra (1961-2004), AC Frua (1965-1973)";
            string[] array = sentence.Split(',');
            CarModel carModel = new CarModel();
            foreach(var item in array)
            {
                var carDataSource = _context.CarTable.Where(x => EF.Functions.Like(x.CarModelName, $"%{item}%")).Select(x => x.CarId);
                foreach(var id in carDataSource)
                {
                    carModel.CarId = id;
                    _context.CarModel.Add(carModel);
                    _context.SaveChanges();
                }
            }
            return null;
        }

您可以使用

var results = Regex.Matches(text, @"\bAC\s+(.*?)\s+\(")
    .Cast<Match>()
    .Select(x => x.Groups[1].Value)
    .ToList();

详情

  • \b - 单词边界
  • AC - AC
  • \s+ - 1+ 个空格
  • (.*?) - 第 1 组(.Groups[1].Value 将保留此子匹配):除换行符以外的任何 0 个或多个字符,尽可能少(因为 *? 是惰性的量词)
  • \s+ - 1+ 个空格
  • \( - 一个 ( 个字符。

参见 regex demo: