Regex.Replace在html字符串中查找变量宽度和高度,并替换为设置值

时间:2011-11-15 22:30:46

标签: c# asp.net regex

我正在尝试编写一个正则表达式来查找字符串中的width和height属性(它始终是一个html iframe)并替换它所具有的值。

我所拥有的是一个字符串,其中###可以是任何值,并且不一定总是3位数。

string iFrame = <iframe width="###" height="###" src="http://www.youtube.com/embed/xxxxxx" frameborder="0" allowfullscreen></iframe>

我想最终得到宽度和高度的设定值:

<iframe width="315" height="215" src="http://www.youtube.com/embed/xxxxxx" frameborder="0" allowfullscreen></iframe>

我试过这个,但对正则表达式不太好:

iFrame = Regex.Replace(iFrame, "width=\".*\"", "width=\"315\"");
iFrame = Regex.Replace(iFrame, "height=\".*\"", "height=\"215\"");

导致:

<iframe width="315" allowfullscreen></iframe>

这不是我想要的。有人能帮助我吗?

3 个答案:

答案 0 :(得分:8)

将您的模式替换为:

  

“宽度= \”([0-9] {1,4})\ “”

  

“高度= \”([0-9] {1,4})\ “”

基本上,您使用的是执行贪婪捕获的.。意思是它抓住尽可能多的角色。上面的模式会查找任意数字字符[0-9],该字符重复1到4次{1,4}。这是你真正想要的。

答案 1 :(得分:3)

最好使用HTML Agility Pack来解析和查询HTML。它可以很好地处理HTML片段。

RegEx不是解析HTML的好方法,因为this SO answer可能会说服你。

答案 2 :(得分:3)

我同意这不是使用html的最佳方式。你的例子的问题是。你正则表达式匹配所有字符和空格直到最后一个“在字符串中。将其更改为下面的代码,只匹配非空白字符。

iFrame = Regex.Replace(iFrame, @"width=""[^\s]*""", "width=\"315\"");
iFrame = Regex.Replace(iFrame, @"height=""[^\s]*""", "height=\"215\"");