我正在做一个类似标签的字符串匹配函数,其中函数检查字符串包含任何可能的单词,同时保持它们的顺序,至少每个标签。我发现最好预先创建可能性列表并在检查时简单地查看字符串是否包含每个所需的组合
也许代码会让它更清晰。
List<List<string[]>> tags;
List<string[]> innerList;
List<List<string>> combinationsList;
public void Generate(string pattern)
{
// i will add whitespace removal later so it can be ", " instead of only ","
foreach (string tag in pattern.Split(','))
{
innerList = new List<string[]>();
foreach (var varyword in tag.Split(' '))
{
innerList.Add(varyword.Split('|'));
}
}
// atm i lack code to generate combinations in form of List<List<string>>
// and drop them into 'combinationsList'
}
// the check function will look something like isMatch = :
public bool IsMatch(string textToTest)
{
return combinationsList.All(tc => tc.Any(c => textToTest.Contains(c)));
}
因此,例如模式:
“老|年轻的约翰|鲍勃,有|拥有狗|猫”
- 标签:
- 列表_1:
- {老,年轻}
- {约翰,鲍勃}
- 列表_2
- {拥有,拥有}
- {狗猫}
- 列表_1:
所以combinationsList将有:
- 组合列表:
- 列表_1
- “老约翰”
- “老鲍勃”
- “小约翰”
- “年轻的鲍勃”
- 列表_2
- “养狗”
- “养猫”
- “养狗”
- “拥有猫”
- 列表_1
所以结果将是:
- old bob have cat = true,包含 List_1:"old bob" 和 List_2:"have cat"
- 年轻的约翰有 car = false,包含 List_1:"young john" 但不包含任何 List_2 组合
我无法弄清楚如何迭代集合以获取这些组合以及如何在每次迭代中获取组合。我也不能把订单搞乱,所以老约翰也不会像老约翰那样生成。
请注意,模式中的任何“变体词”都可能有两个以上的变体,例如“dog|cat|mouse”