我想要加密HTML文檔的文本內容而不更改其佈局。內容存儲在成對的標記中,如下所示:< span style ...> text_to_get </span>。我的想法是使用正則表達式來檢索(1)並用加密文本(2)替換每個文本部分。我完成了步驟(1),但在步驟(2)中遇到了麻煩。這裏是代碼我工作:使用正則表達式替換HTML標記內容
private string encryptSpanContent(string text, string passPhrase, string salt, string hash, int iteration, string initialVector, int keySize)
{
string resultText = text;
string pattern = "<span style=(?<style>.*?)>(?<content>.*?)</span>";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(resultText);
foreach (Match match in matches)
{
string replaceWith = "<span style=" + match.Groups["style"] + ">" + AESEncryption.Encrypt(match.Groups["content"].Value, passPhrase, salt, hash, iteration, initialVector, keySize) + "</span>";
resultText = regex.Replace(resultText, replaceWith);
}
return resultText;
}
這是錯行(這使得由最後replaceWith值取代了所有文本)?
resultText = regex.Replace(resultText, replaceWith);
有人能幫我解決這個問題嗎?
不要用正則表達式解析HTML一個簡單的解決方案。 http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – David 2012-03-19 17:24:18