2012-09-29 31 views
-1

HTML源C#Regex.Matches HTML如php preg_match_all

<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#代碼? 謝謝!

+0

[just code](http://stuck.include-once.org/#help5)的請求通常是無關緊要的。主要網站意圖是編碼方法,而不是現成的解決方案,本身也不是[tutoring](http://stuck.include-once.org/#help6)。 – hakre

回答

1

的問題你的HTML是你省略了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); 
} 

然而,隨着L.B說,使用專用的HTML解析器,而不是正則表達式,因爲HTML不能保證是有效的XML,可能包含不同的佈局和編碼等。

如果你必須使用正則表達式,他們需要變得更靈活。例如,屬性和元素之間可能有更多或不同的空白。

+0

太棒了!絕對正確,這是我想要的。 – user808186

3

如果你想與你的正則表達式與真正的Html parser來分析,而不是regex

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); 
+0

再次再次感謝!它的工作! 我是添加過濾器類型不隱藏的元素。 var dict = doc.DocumentNode .Descendants(「input」)。Where(n => n.Attributes [「type」]!= null && n.Attributes [「type」]。Value ==「hidden」) .ToDictionary(n => n.Attributes [「name」]。Value,n => n.Attributes [「value」]。Value); – user808186