我想在不更改布局的情况下加密 HTML 文档的文本内容。内容以标签对的形式存储,如下所示:text_to_get。我的想法是使用 Regex 检索 (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);
谁能帮我解决这个问题?
最佳答案
建议您使用 HTML Agility Pack如果您打算使用 HTML,因为您可能会遇到正则表达式问题,尤其是在嵌套标签或格式错误的 HTML 上。
假设您的 HTML 格式正确并且您决定使用正则表达式,您应该使用 Regex.Replace
method接受 MatchEvaluator
来替换所有匹配项。
试试这个方法:
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
使用了一个 lambada 表达式,并引用了如上所示的“content”组。我还对 span
标记使用环视,以避免必须将它们包含在替换模式中。
关于c# - 使用正则表达式替换 HTML 标记内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9773962/