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

本文关键字:样式 删除 元素 何使用 正则表达式 | 更新日期: 2023-09-27 17:55:21

我试图从内联样式中删除一个属性,即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, "");

这将删除所有内联样式。如何移除浮子?

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

这应该删除所有浮点数:

data = Regex.Replace(data, @"(style='"".*?)(float:'s*[^;'""]+;?)(.*?'"")", "$1$3", RegexOptions.IgnoreCase)

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

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 + @"""";
    }));

此代码仅从样式元素中删除浮点属性

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

我们可以通过 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 plus regex replace method:
优点:只需要匹配浮动而不是样式和浮动

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);

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

(float:.*?;)
1.  float:right;
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, "");