我已经在解决这个问题上有一段时间了,希望我能对此有所解决。
我有一句话,其中包含我想提取的关键信息。
一旦提取了这些字符串,我会将它们保存为数组,然后将这些字符串与数据库中存在的字符串进行比较。
我遇到的问题是成功提取了字符串。
例如,我有这句话:
These are a list of automobiles along with their production dates: AC 3000ME (1979-1984), AC Shelby-Cobra (1961-2004), AC Frua (1965-1973)
。
我想提取:3000ME
,Shelby-Cobra
和Frua
。
这是下面的代码:
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;
}
答案 0 :(得分:2)
您可以使用
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: