如何根据第一个列表匹配检索子字符串
本文关键字:检索 字符串 列表 何根 第一个 | 更新日期: 2023-09-27 18:01:33
在字符串中,我需要根据列表中任何项的第一个匹配恢复7个字符的子字符串。如果没有匹配,它应该返回一个空字符串。
我有以下代码:
List<string> myList = new List<string>()
{
"TNCO",
"TNCB",
"TNIT"
};
string sample = "TNSD102, WHRK301, TNIT301, YTRE234";
//doesn't give an index
bool anyfound = myList.Any(w => sample.Contains(w));
//code that needs replacing
string code = sample.Substring(sample.IndexOf("TNC"), 7);
if (code == "")
{
code = sample.Substring(sample.IndexOf("TNIT"), 7);
}
列表不可能超过35-40个项目,字符串<50个字符。
谁能给我指个正确的方向?string val1 = (sample.Split(',').FirstOrDefault(w => myList.Any(m => w.Contains(m))) ?? string.Empty).Trim();
这将为您提供所有匹配的IEnumerable:
var matches = from code in sample.Split(',')
from w in myList
where code.Trim().StartsWith(w)
select code;
使用FirstOrDefault获取第一个值。如果没有匹配,则使用合并运算符??
返回空字符串。
string firstMatch = (matches.FirstOrDefault() ?? "").Trim();
对于这么小的数据集,您可以简单地拆分字符串并搜索第一个匹配:
// split the sample string into separate entries
var entries = sample.Split(new char[] {',', ' '},
StringSplitOptions.RemoveEmptyEntries);
// find the first entry starting with any allowed prefix
var firstMatch = entries.FirstOrDefault (
e => myList.Any (l => e.StartsWith(l)));
// FirstOrDefault returns null if there are no matches
if (firstMatch == null)
Console.WriteLine("No match!");
else
Console.WriteLine(firstMatch);
示例输出(DEMO):
TNIT301
List<string> myList = new List<string> { "TNCO", "TNCB", "TNIT" };
string sample = "TNSD102, WHRK301, TNIT301, YTRE234";
string[] sampleItems = sample.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
var results = myList
.Select(prefix => sampleItems
.FirstOrDefault(item => item.StartsWith(prefix)) ?? "");
运行此代码将返回一个索引2,该索引基于您要查找的内容。
int keyIndex = myList.FindIndex(w => samples.Contains(w));
TNIT301
这是索引字符串值
您还可以执行以下操作来返回keyIndex
变量value索引位置的字符串值。
var subStrValue = samples.Split(',')[keyIndex];