regex to replace self closing html tags in c#

老子叫甜甜 提交于 2021-02-04 21:07:26

问题


I have an xml which contains some html tags also. When a tag comes in, it breaks the page because it's a self closing tag. Something like:

<iframe width="420" height="315" src="//www.youtube.com/embed/6krfYKxJFqA" frameborder="0" />

I want to replace this and convert it to:

Can anyone provide a c# code with regex to do this. I tried doing:

tmp = tmp.Replace("(<iframe[^>]*)(\\s*/>)", "$1></iframe>");

and

tmp = new Regex(@"(<iframe[^>]*)(\\s*/>)").Replace(tmp, "$1></iframe>");

tmp is the xml containing lot of code + this iframe tag as string.

but with no result.


回答1:


In the second regex, you don't need the double backslash as you are using @.

Also, (<iframe[^>]*) also matches the last /, use the non-greedy ? operator: (<iframe[^>]*?)(\s*/>)




回答2:


Try this as a match expression:

<iframe(.*?)(["\d\w\s])\/>

note that you can use http://regexpal.com/ to test regex, it's super convenient.



来源:https://stackoverflow.com/questions/21845886/regex-to-replace-self-closing-html-tags-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!