使用正则表达式替换HTML标签内容

3

我想加密HTML文档中的文本内容,而不改变其布局。内容以标签对形式存储,如下所示:<span style...>text_to_get</span>。我的想法是使用正则表达式检索(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);

有人能帮我解决这个问题吗?

1
不要使用正则表达式解析HTML。https://dev59.com/X3I-5IYBdhLWcg3wq6do - David
2个回答

3

如果你要处理HTML,建议使用HTML Agility Pack,因为使用正则表达式可能会遇到嵌套标签或格式不正确的HTML等问题。

假设你的HTML格式正确并决定使用正则表达式,则应该使用接受MatchEvaluator参数的Regex.Replace方法来替换所有出现的内容。

可以尝试以下方法:

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

在这里,我使用lambda表达式作为MatchEvaluator,并像上面所示一样引用“content”组。我还使用前后查找来匹配span标签,以避免将它们包含在替换模式中。


哦,我该如何用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; - Minh Nguyen

-2

这里有一个简单的解决方案,用于替换HTML标签

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

2
虽然这是一种粗略正确的匹配HTML标签的方法,但它不会将每个不同的标签替换为特定的字符串,实质上您会将所有标签都合并为一种类型,从而丢失重要信息。 - Superbest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接