我有这个示例字符串:
var content = "Lorem ipsum dolor sit amet <a href=\"mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a0a7afa689b1b1b1e7aaa6a4" rel="noreferrer noopener nofollow">[email protected]</a>\"><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec7c0c8c1eed6d6d680cdc1c3" rel="noreferrer noopener nofollow">[email protected]</a></a> ipsum dolor <a href=\"mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb82858d84ab929292c58e9e" rel="noreferrer noopener nofollow">[email protected]</a>\"><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="274e494148675e5e5e094252" rel="noreferrer noopener nofollow">[email protected]</a></a> adipiscing elit.";
当字符串包含 mailto-link 时,我想替换(操作)所有出现的 a 标记。
anchor 在操作后应该看起来像:
<a href="#" title="protected"><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="375e591919774f4f4f1954585a" rel="noreferrer noopener nofollow">[email protected]</a></a>
内容字符串可以包含任意数量的邮件链接。
我怎样才能最好地完成这项任务?
最佳答案
如果您有 XHTML,则使用 XElement,如 Chuck 所示。
如果没有,那么正则表达式就是最佳选择。类似于:
Regex find = new Regex("<a\\b[^>]*href=['\"]mailto:(.*?)['\"]", RegexOptions.Singleline | RegexOptions.IgnoreCase);
警告,我没有测试上面的代码,但我 99% 确定它是正确的。另外,我可能错过了一个极端的情况,例如电子邮件地址中的 >。
关于c# - 替换邮件链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11281432/