如何使用正则表达式从内联样式中删除样式元素?

How do I remove a style element from an inline style using regex?

提问人:user3457760 提问时间:6/12/2015 最后编辑:shet_tayyyuser3457760 更新时间:3/31/2023 访问量:8444

问:

我试图从内联样式中只删除一个属性,即及其值。我想从这个开始:float

<div id="first_line_info" style="width:490px; float:right;"> </div>

并把它做成这样:

<div id="first_line_info" style="width:490px"> </div>

到目前为止,我已经尝试了以下代码:

Regex noInlineStylePattern = new Regex("style=\"[^\"]*\"", RegexOptions.IgnoreCase);
data = noInlineStylePattern.Replace(data, "");

这将删除所有内联样式。我怎样才能删除浮子?

JavaScript C# HTML CSS 正则表达式

评论

0赞 AlliterativeAlice 6/12/2015
您要删除什么?仅 ?有什么风格吗?除 ?float:right;floatwidth
0赞 user3457760 6/12/2015
我想删除所有浮点数并保留宽度。我正在使用的文档 HTML 中有多个浮点数。
33赞 Ken White 6/13/2015
此外,您可能还想看看嗨、谢谢、标语和称呼是否应该从帖子中删除?
0赞 Yvonne Aburrow 4/2/2019
为什么不删除所有内联样式并将它们替换为 CSS 中的类呢?
12赞 CervEd 5/9/2020
起初我想知道为什么这个问题有这么多反对票,然后我看了历史

答:

16赞 AlliterativeAlice 6/12/2015 #1

这应该会删除所有浮点数:

data = Regex.Replace(data, @"(style=\"".*?)(float:\s*[^;\""]+;?)(.*?\"")", "$1$3", RegexOptions.IgnoreCase)
11赞 Oleg 6/12/2015 #2

此代码删除 style 元素中除第一个属性之外的所有属性

string test = @" <div id=""first_line_info"" style=""width:490px; float:right;""> </div>";

var result = Regex.Replace(test,"(style=\")(.*?;).*\"", new MatchEvaluator((m)=>
    {
        return m.Groups[1].Value + m.Groups[2].Value + @"""";
    }));

此代码仅从 style 元素中删除 float 属性

var result2 = Regex.Replace(test, "(style=\".*?;).*(float:.*?;)\"", new MatchEvaluator((m) =>
    {
        return m.Groups[1].Value + @"""";
    }));
4赞 vusan 5/19/2017 #3

我们可以通过 DOM 操作实现相同的目的:

var dom = document.createElement('div');
dom.innerHTML = `
  <div id="first_line_info" style="width:490px; float:right;"> </div>
  <div id="first_line_info1" style="width:490px;float:left;float:right"> </div>
`;
var elem = dom.getElementsByTagName('div');
var len = elem.length;

for (var i = 0; i < len; i++) {
  elem[i].style.float = null;
  //float removed
}

console.log(dom.innerHTML);

从 dom-manipulation 加正则表达式替换方法: 优点:
只需要匹配 float 而不是样式和 float

var dom = document.createElement('div');
dom.innerHTML = `
  <div id="first_line_info" style="width:490px; float:right;"> </div>
  <div id="first_line_info1" style="width:490px; float:right;float:left"> </div>
`;
var elem = dom.getElementsByTagName('div');
var len = elem.length;

for (var i = 0; i < len; i++) {
  var style = elem[i].getAttribute('style');
  var regex = /(float:\w+;*)/g;

  style = style.replace(regex, "");
  //float removed

  elem[i].setAttribute('style', style);
}

console.log(dom.innerHTML);
0赞 Abimanyu 4/2/2019 #4

在匹配组值中,您可以替换它。

(float:.*?;)

1.  float:right;
-1赞 Feng 3/31/2023 #5
string data = "<div id=\"first_line_info\" style=\"width:490px; float:right;\"> </div>";
Regex floatPattern = new Regex(@"float\s*:\s*\w+\s*;?", RegexOptions.IgnoreCase);
data = floatPattern.Replace(data, "");

评论

3赞 user67275 3/31/2023
请为您的代码添加一些解释,而不是仅发布代码。额外的解释会更有帮助。