【问题标题】:Replace HTML tag content using Regex使用正则表达式替换 HTML 标记内容
【发布时间】:2012-04-04 03:53:34
【问题描述】:

我想加密 HTML 文档的文本内容而不更改其布局。内容以成对的标签存储,如下所示:text_to_get。我的想法是使用正则表达式来检索 (1) 并用加密文本 (2) 替换每个文本部分。我完成了第 (1) 步,但在第 (2) 步遇到了麻烦。这是我正在处理的代码:

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);

谁能帮我解决这个问题?

【问题讨论】:

标签: c# .net html regex replace


【解决方案1】:

如果您要使用 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 使用了lambda 表达式,并引用了如上所示的“内容”组。我还对span 标记使用环视,以避免将它们包含在替换模式中。

【讨论】:

  • 哦,我怎样才能用 Java 编写这些行?我发现 Java 中的正则表达式比 C# 中的“更糟糕”。 String text = Text; String pattern = "&lt;span style=(?&lt;style&gt;.*?)&gt;(?&lt;content&gt;.*?)&lt;/span&gt;"; text = Regex.Replace(text, pattern, m =&gt; "&lt;span style=" + m.Groups["style"] + "&gt;" + Decrypt(m.Groups["content"].Value, PassPhrase, Salt, Hash, Iterations, InitialVector, KeySize) + "&lt;/span&gt;"); return text;
【解决方案2】:

这里是替换 HTML 标签的简单解决方案

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

【讨论】:

  • 虽然这是匹配 HTML 标签的大致正确方法,但它不会用特定的字符串替换每个不同的标签,基本上你会将所有标签折叠为一种类型,从而丢失重要信息。
猜你喜欢
  • 2016-04-06
  • 2011-06-28
  • 1970-01-01
  • 2014-10-28
  • 2011-05-05
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
相关资源
最近更新 更多