2012-03-19 159 views
3

我想要加密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); 

有人能幫我解決這個問題嗎?

+1

不要用正則表達式解析HTML一個簡單的解決方案。 http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – David 2012-03-19 17:24:18

回答

3

如果您打算使用HTML,建議您使用HTML Agility Pack,因爲您可能遇到正則表達式問題,尤其是嵌套標記或格式錯誤的HTML。

假設您的HTML格式正確,並且您決定使用正則表達式,則應使用接受MatchEvaluatorRegex.Replace method來替換所有出現的事件。

嘗試這種方法:

string input = @"<div><span style=""color: #000;"">hello, world!</span></div>"; 
string pattern = @"(?<=<span style=""[^""]+"">)(?<content>.+?)(?=</span>)"; 
string result = Regex.Replace(input, pattern, 
    m => AESEncryption.Encrypt(m.Groups["content"].Value, passPhrase, salt, hash, iteration, initialVector, keySize)); 

在這裏,我使用蘭巴達表達爲MatchEvaluator和如上所示參閱「內容」基團。我還使用環視span標籤來避免將它們包含在替換模式中。

+0

感謝您的建議。 MatchEvaluator的作品。 – 2012-03-22 09:01:11

+0

哦,我該如何在Java中編寫這些行?我發現Java中的正則表達式比C#中的「更糟糕」。 'String text = Text; String pattern =「。*?)>(?。*?)」; text = Regex.Replace(text,pattern, m =>「」+ Decrypt(m.Groups [「content」]。Value,PassPhrase, Salt,Hash,Iterations,InitialVector,KeySize)+「」); return text;' – 2012-05-03 14:25:17

-2

這裏是取代HTML標籤

string ReplaceBreaks(string value) 
{ 
    return Regex.Replace(value, @"<(.|\n)*?>", string.Empty); 
} 
+2

雖然這是匹配HTML標籤的一種大致正確的方式,但它不會用特定的字符串替換每個不同的標籤,實質上,您會將所有標籤摺疊爲一種類型,從而失去重要信息。 – Superbest 2012-09-27 02:02:39

相關問題