HtmlAgilityPackを使用してそれを行う方法の例を次に示します。それでも正規表現を使用したい場合は、回答の他の部分を参照してください。
string html = @"<option foo1='bar1' value=""1"" foo=bar></option>";
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var node = doc.DocumentNode.ChildNodes[0];
//Get all the attributes
var attributes = new List<HtmlAttribute>(node.Attributes);
//Remove all the attributes
node.Attributes.RemoveAll();
//Insert them again
foreach (var attr in attributes) {
//If we found the 'value' atrribute, insert it at the begining
if (attr.Name == "value")
{
node.Attributes.Insert(0, attr);
}
else {
node.Attributes.Add(attr);
}
}
Console.WriteLine(doc.DocumentNode.OuterHtml);
上記のコードは次のように表示されます。
<option value="1" foo="bar" foo1='bar1'>
それはほんの一例でした。HTML のすべてのノードに対してそれを行うことも、必要なノードだけにそれを適用することもできます。
正規表現を使用した別の例。ニーズに 100% 一致するように変更する必要がある場合があります。
string regex = @"<([\w]+)\s+(?:(\w+)=[""']?([^\s""']+)[""']?\s*)+>";
string html = @"<option foo=bar value=""1"" foo2='bar2'>...</option>
<option foo=bar value=""1"" foo2='bar2'>...</option>
<option foo=bar value=""1"" foo2='bar2'>...</option>";
//Getting all the matches.
var matches = Regex.Matches(html, regex);
foreach (Match m in matches) {
//This will contain the replaced string
string result = string.Format("<{0}", m.Groups[1].Value);
//Here we will store all the keys
var keys = new List<string>();
//Here we will store all the values
var values = new List<string>();
//For every pair (key, value) matched
for (int i = 0; i < m.Groups[2].Captures.Count; i++) {
//Get the key
var key = m.Groups[2].Captures[i].Value;
//Get the value
var value = m.Groups[3].Captures[i].Value;
//Insert on the list (if key is 'value', insert at the beginning)
if (key == "value") {
keys.Insert(0, key);
values.Insert(0, value);
}
else {
keys.Add(key);
values.Add(value);
}
}
//Concatenate all the (key, value) attributes to the replaced string
for (int i = 0; i < keys.Count; i++) {
result += string.Format(@" {0}=""{1}""", keys[i], values[i]);
}
//Close the tag
result += ">";
Console.WriteLine(result);
}
それは印刷されます:
<option value="1" foo="bar" foo2="bar2">
<option value="1" foo="bar" foo2="bar2">
<option value="1" foo="bar" foo2="bar2">