Skip to main content
 首页 » 编程设计

c#之正则表达式替换标签以制作有效的html

2024年02月04日29落叶无声

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

[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 标记。

请您参考如下方法:

Regex.Replace(htmlSource, @"\[(\/*caption.*?)\]", @"<$1>") 

参见 Demo