我正在寻找一个RegEx来从特定标签内的特定属性中删除参数值。例如正则表达式从标签中删除特定的参数
<TAG1 atr1="param1: value1; param2: value; param3: value3;" attr2="value4">
<TAG2 attr2="value4" atr1="param1: value1; param2: value; param3: value3;" >
应导致
我正在寻找一个RegEx来从特定标签内的特定属性中删除参数值。例如正则表达式从标签中删除特定的参数
<TAG1 atr1="param1: value1; param2: value; param3: value3;" attr2="value4">
<TAG2 attr2="value4" atr1="param1: value1; param2: value; param3: value3;" >
应导致
HEIGHT: \d+[^;]+;
将在<body style="HEIGHT: 218px; margin: 0px; background-color: #ffffff;" jQuery111105496473080628138="10">
事情是这样的匹配HEIGHT: 218px;
可以让你去: (HEIGHT:\s*\d{1,}[^;]*;)(?<=<body.*style="[^"]*)(?=[^"].*"\s*>)
其中〜翻译〜到:
捕获:(HEIGHT:\s*\d{1,}[^;]*;)
如果前面有:(?<=<body.*style="[^"]*)
并通过如下:(?=[^"].*"\s*>)
实现代码:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
static void Main(string[] args)
{
string string1 = "<body style=\"HEIGHT: 218px; margin: 0px; background-color: #ffffff;\" jQuery111105496473080628138=\"10\">";
string string2 = "<body jQuery111105496473080628138=\"10\" style=\"HEIGHT: 218px; margin: 0px; background-color: #ffffff;\" >";
string string3 = "<test style=\"HEIGHT: 218px; margin: 0px; background-color: #ffffff;\" jQuery111105496473080628138=\"10\">";
List<string> theList = new List<string> { string1, string2, string3 };
Regex heightMatchingRegex = new Regex("(HEIGHT:\\s*\\d{1,}[^;]*;)(?<=<body.*style=\"[^\"]*)(?=[^\"].*\"\\s*>)");
foreach (string item in theList)
{
if (heightMatchingRegex.IsMatch(item))
{
Console.WriteLine("The match: " + heightMatchingRegex.Match(item));
Console.WriteLine("Original: " + item);
Console.WriteLine("Modified: " + heightMatchingRegex.Replace(item, ""));
}
}
Console.ReadLine();
}
尝试一下小提琴: https://dotnetfiddle.net/CIgByr
谢谢! –
好的,你到目前为止尝试过什么? – chris85
我是新来的Regex。获得以下 (
) 但它删除整个STYLE属性,如果它与BODY标记相邻 –SO错误的地方...一般来说,尝试使用正则表达式解析HTML是非常不友好的,请考虑在其他地方寻找 –