正则表达式替换标签来制作有效的HTML

问题描述 投票:1回答:1

我想转换下面提到的标签:

[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]标签转换为<caption>。这样它就变成了一个有效的html标签,然后使用html agility pack来解析标签。

下面是C#代码:

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

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

c# regex regex-negation
1个回答
4
投票
Regex.Replace(htmlSource, @"\[(\/*caption.*?)\]", @"<$1>")

Demo

© www.soinside.com 2019 - 2024. All rights reserved.