c# - 在 C# 中使用正则表达式删除 css 样式

标签 c# css asp.net regex styles

我想在 c# 中编辑来自 html 标签的宽度属性和来自字符串的内联样式 例如将 width="54px"(或 style="width:54px")转换为 width="54px"或(style="width:100%") 在我的字符串中可能有这样的宽度:width='54px'(不带双引号) 像这样:

<div width= " 25px " ></div>
<div Width= " 63453px   "   ></div>
<div width='15px' ></div>
<div width= ' 15px' ></div>
<div Width= ' 15px' ></div>
<div width="1 "  ></div>
<div Width=  " 45"></div>
<div width="  5454px  "></div>
<div width="54px"></div>
<div width="54px" style="width:54px"> </div>

我尝试用这种方法来做到这一点:

  public string _ConvertTagWidth2(string content)
{
    string patern1 = "width=\".\\w*\"";
    string patern2 = "width='.\\w*'";

    string replace1 = "width=\"100%\"";
    string replace2 = "width:'100%'";

    string output = Regex.Replace(content, patern1, replace1, RegexOptions.IgnoreCase);
    output = Regex.Replace(output, patern2, replace2, RegexOptions.IgnoreCase);

    return output;
}

但是结果是这样的:

<div width= " 25px " ></div>
<div Width= " 63453px   "   ></div>

<div width:'100%' ></div>
<div width= ' 15px' ></div>
<div Width= ' 15px' ></div>

<div width="1 "  ></div>
<div Width=  " 45"></div>

<div width="  5454px  "></div>
<div width="100%"></div>
<div width="100%" style="width:54px"> </div>

我怎样才能修复正则表达式来做这个解决方案

最佳答案

我在regular tester的帮助下解决了

(宽度=)(\s+"|")(\d+px"|\s+\d+px"|\s+\d+px\s+"|\d+px\s+")

关于c# - 在 C# 中使用正则表达式删除 css 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26466488/

相关文章:

c# - Entity Framework 无效对象名称错误

javascript - Bootstrap Modal 使用数据图像作为源

c# - INSERT 语句与 FOREIGN KEY 约束错误冲突

c# - Response.Flush() 抛出 System.Web.HttpException

asp.net - ASP.NET HttpRequest 可以为空吗? CurrentExecutionFilePath 怎么样?

javascript - 如何在asp.net中从c#执行javascript

c# - DateTime 表示和转换显示错误的日期

c# - 如何取消异步调用?

css - 使用游标 Sprite

html - 可滚动、固定高度的表格