gpt4 book ai didi

c# - Regex.Replace 在 html 字符串中查找可变宽度和高度并替换为设置值

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:20 27 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来查找字符串中的宽度和高度属性(它始终是一个 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>

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

最佳答案

将你的模式替换为:

"width=\"([0-9]{1,4})\""

"height=\"([0-9]{1,4})\""

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

关于c# - Regex.Replace 在 html 字符串中查找可变宽度和高度并替换为设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8144082/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com