-1

htmlソース

<form>
<input type="text" name="a" value="a1fa4" type="hidden"/>
<input type="text" name="b" value="b1fa9" type="hidden"/>
<input type="text" name="c" value="c1fd2" type="hidden"/>
<input type="text" name="d" value="d1fx1" type="hidden"/>
</form>

phpソース

<?php
  preg_match_all('/<input name="(.*?)" value="(.*?)" type="hidden"\/>/i', $form, $input);

  $var = array();

  for($i=0;$i<count($input[1]);$i++){
    $var[$input[1][$i]] = $input[2][$i];
  }
?>

C#ソース

Match match = Regex.Match(html, "<input name=\"(.*?)\" value=\"(.*?)\" type=\"hidden\"/>", RegexOptions.IgnoreCase );
while (match.Success)
{
    System.Console.WriteLine(" {0} {1} ", match.Value, match.Index);  
}

phpコードは機能しますが、c#コードは機能しません。どうすればC#コードを修正できますか?ありがとう!

4

2 に答える 2

3

正規表現の代わりに実際のHtmlパーサーを使用してHTMLを解析する場合

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);

var dict =  doc.DocumentNode
       .Descendants("input")
       .ToDictionary(n=>n.Attributes["name"].Value,n=>n.Attributes["value"].Value);
于 2012-09-29T08:32:28.503 に答える
1

正規表現の問題は、を省略したことtype=\"text\"です。次の作品:

string html =
    @"<form>
    <input type=""text"" name=""a"" value=""a1fa4"" type=""hidden""/>
    <input type=""text"" name=""b"" value=""b1fa9"" type=""hidden""/>
    <input type=""text"" name=""c"" value=""c1fd2"" type=""hidden""/>
    <input type=""text"" name=""d"" value=""d1fx1"" type=""hidden""/>
    </form>";

foreach(Match match in Regex.Matches(html, 
    "<input type=\"text\" name=\"(.*?)\" value=\"(.*?)\" type=\"hidden\"/>", 
        RegexOptions.IgnoreCase))
{
    // Group 0 is the string matched so get groups 1 and 2.
    System.Console.WriteLine("Name={0} Value={1} ", match.Groups[1].Value, 
        match.Groups[2].Value);
}

ただし、LBが言うように、HTMLは有効なXMLであることが保証されておらず、異なるレイアウトやエンコーディングなどが含まれている可能性があるため、正規表現の代わりに専用のHTMLパーサーを使用してください。

正規表現を使用する必要がある場合は、より柔軟である必要があります。たとえば、属性と要素の間に空白が多い場合や異なる場合があります。

于 2012-09-29T08:48:55.050 に答える