2012-03-19 164 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

相关问题