简单的正则表达式对此应该没问题。
private Dictionary<string,string> ParseCommentVariables(string contents)
{
Dictionary<string,string> variables = new Dictionary<string,string>();
Regex commentParser = new Regex(@"<!--.+?-->", RegexOptions.Compiled);
Regex variableParser = new Regex(@"\b(?<name>[^:]+):\s*""(?<value>[^""]+)""", RegexOptions.Compiled);
var comments = commentParser.Matches(contents);
foreach (Match comment in comments)
foreach (Match variable in variableParser.Matches(comment.Value))
if (!variables.ContainsKey(variable.Groups["name"].Value))
variables.Add(variable.Groups["name"].Value, variable.Groups["value"].Value);
return variables;
}
将首先从“内容”字符串中提取所有评论。然后它将提取它找到的所有变量。它将这些存储在字典中并将其返回给调用者。
IE:
string contents = "some other HTML, lalalala <!-- variable1: \"wer2345235\" variable2: \"sdfgh333\" variable3: \"sdfsdfdfsdf\" --> foobarfoobarfoobar";
var variables = ParseCommentVariables(contents);
string variable1 = variables["variable1"];
string variable2 = variables["variable2"];