簡單的正則表達式應該適用於此。
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;
}
將首先提取'contents'字符串中的所有註釋。然後它會提取它找到的所有變量。它將它們存儲在字典中並將其返回給調用者。
即:
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"];
您可以使用隱藏域呢?可能會讓生活更輕鬆。或者這是其他人做出評論意見的情況,而且你試圖找到一種方法使其發揮作用? – peroija
它實際上是爲了響應來自我的web應用程序的HTTP帖子而生成的。這是一個簡單確認數據提交的API響應。不幸的是我無法改變。 –
我們這樣做是爲了解析內部部署的原始服務器名稱和安裝的應用程序版本。我們使用正則表達式來解析通過ajax調用返回的html。匹配評論。然後使用組拉出變量。 –