【问题标题】:How do I remove a style element from an inline style using regex?如何使用正则表达式从内联样式中删除样式元素?
【发布时间】:2015-08-27 18:26:37
【问题描述】:

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

这会删除所有的内联样式。我怎样才能删除浮动?

【问题讨论】:

  • 您要删除什么?只有float:right; 的实例?任何float 风格?除了width之外的所有样式?
  • 我想删除所有的浮动并保留宽度。我正在使用的文档 HTML 中有多个浮点数。
  • 为什么不删除所有的内联样式并用 CSS 中的类替换它们?
  • 起初我想知道为什么这个问题有这么多反对票,然后我查看了历史

标签: javascript c# html css regex


【解决方案1】:

这应该删除所有浮动:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案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 而不是 style 和 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);
      

      【讨论】:

        【解决方案4】:

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

        (float:.*?;)
        
        1.  float:right;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-05
          • 1970-01-01
          • 2020-03-24
          • 1970-01-01
          • 1970-01-01
          • 2014-12-20
          相关资源
          最近更新 更多