我有一个KeyStrings列表:
List<string> KeyStrings = new List<string>
{
"Can you give me a @key for @key",
"I need @number of gold to buy a @key",
"@key\r\n@key\r\nCount: @number",
};
在这个字符串中我们有一些KeyWord变量(@key和@number)。
另一方面,我们有一个简单的字符串
var sample = "Item\r\nThis item description\r\nYou can use this item to do somthing\r\nCount: 5";
此示例等于KeyString
"@key\r\n@key\r\nCount: @number"
从列表中,
@key : "Item",
@key : "This item description\r\nYou can use this item to do something",
@number : 5.
我已经写了一些使用Regex查找KeyWords值的方法。
public static List<KeyValuePair<string, string>> GetKeysValue(string template, string str)
{
List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
string pattern = Regex.Escape(template);
MatchCollection matches;
int count = 0;
while ((matches = Regex.Matches(pattern, "@key|@number", RegexOptions.Compiled)).Count != 0)
{
pattern = pattern.Remove(matches[0].Index, matches[0].Length);
pattern = pattern.Insert(matches[0].Index, "(.+?)");
result.Add(new KeyValuePair<string, string>(matches[0].Value, ""));
count++;
}
pattern += "$";
Regex r = new Regex(pattern, RegexOptions.Singleline);
Match m = r.Match(str);
for (int i = 1; i < m.Groups.Count; i++)
{
var key = result[i - 1].Key;
result[i - 1] = new KeyValuePair<string, string>(key, m.Groups[i].Value);
}
return result;
}
但是我找不到列表中搜索KeyString的好解决方案。我尝试使用FuzzyString库,但在我的情况下,字符串非常不同。