我正在尋找一個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是非常不友好的,請考慮在其他地方尋找 –