【问题标题】:Regex to replace tags to make valid html正则表达式替换标签以生成有效的 html
【发布时间】:2018-08-11 13:34:30
【问题描述】:

我正在尝试转换下面提到的标签:

[caption id="attachment_812" align="alignleft" width="240"]<img class="wp-
image-92692" src="sample.jpg" alt="" width="316" height="210"/>Sample 
text[/caption]

到下面使用正则表达式:

<caption id="attachment_812" align="alignleft" width="240"><img class="wp-
image-92692" src="sample.jpg" alt="" width="316" height="210"/>Sample 
text</caption>

所以基本上我想将 [caption] 标签转换为&lt;caption&gt;。使其成为有效的html标签,然后使用html敏捷包解析标签。

下面是 C# 代码:

//Replace [caption]
htmlSource = Regex.Replace(htmlSource, @"\[caption]", "<caption>");
//Replace [/caption]
htmlSource = Regex.Replace(htmlSource, @"\[/caption]", "</caption>");

这适用于没有属性的标题标签。我正在寻找一种更好的解决方案,甚至可以保留属性,只需替换方括号即可使其成为有效的 html 标记。

【问题讨论】:

  • 您可能还需要转义关闭的]

标签: c# regex regex-negation


【解决方案1】:
Regex.Replace(htmlSource, @"\[(\/*caption.*?)\]", @"<$1>")

Demo

【讨论】:

  • 让多个标签像这样扩展它:Regex.Replace(htmlSource, @"\[(\/*(caption|img).*?)\]", @"&lt;$1&gt;")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2020-05-22
相关资源
最近更新 更多