提问人:user3457760 提问时间:6/12/2015 最后编辑:shet_tayyyuser3457760 更新时间:3/31/2023 访问量:8444
如何使用正则表达式从内联样式中删除样式元素?
How do I remove a style element from an inline style using regex?
问:
我试图从内联样式中只删除一个属性,即及其值。我想从这个开始: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, "");
这将删除所有内联样式。我怎样才能删除浮子?
答:
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
请为您的代码添加一些解释,而不是仅发布代码。额外的解释会更有帮助。
上一个:单层神经网络 [已关闭]
评论
float:right;
float
width