2012-12-13 106 views
4

我有一個字符串正則表達式匹配問題

<a href="/makeuppro/video?st.cmd=altGroupVideoAll&amp;st.groupId=oqxdtikenuenvnwuj0rxiwhgvyuvhjhzjrd&amp;st.directLink=on&amp;st.referenceName=makeuppro&amp;st._aid=NavMenu_AltGroup_Video"

我需要獲得組ID oqxdtikenuenvnwuj0rxiwhgvyuvhjhzjrd

我試圖

string groupId = Regex.Match(content, @"altGroupVideoAll&amp;st.groupId=(?<id>[^""]+)&amp").Groups["id"].Value; 

但結果是:

oizrximcmbsyyvjxacd0rpkkmgxwuvhinnuvczz&amp;st.directLink=on&amp;st.referenceName=makeuppro 

爲什麼,什麼是正確的正則表達式?

+6

我認爲一個更強大的方法是讓整個URL,然後用像'HttpUtility.ParseQueryString'解析它 – Matthew

回答

4

您需要使用不願意量詞停在第一&amp: -

@"altGroupVideoAll&amp;st.groupId=(?<id>[^""]+?)&amp" 
0

試試這個:

groupId=(?<id>[^&]+) 

我懷疑ID將不包含&字符。您的原始正則表達式很貪婪,並嘗試匹配最長的字符串。

0

海蘭@ user1895750和@Jared哈雷,

你做與懶又饞表達迷惑,看下面的代碼。

/// <summary> 
    /// Example for how to extract the group Id. 
    /// </summary> 
    /// <param name="xml"></param> 
    /// <returns></returns> 
    private static string ExtractNumber(string xml) 
    { 
     // Extracted number. 
     string groupId = string.Empty; 

     // Input text 
     xml = @"<a href=""/makeuppro/video?st.cmd=altGroupVideoAll&amp;st.groupId=oqxdtikenuenvnwuj0rxiwhgvyuvhjhzjrd&amp;st.directLink=on&amp;st.referenceName=makeuppro&amp;st._aid=NavMenu_AltGroup_Video"""; 

     // Here is the key, you have to use "?" after "(?<id>[^\"\"]+" 
     // This is called "Lazy expression", and it is different from the "Greedy expression". 
     // Lazy expression uses the "?", like ".*?\r". So it will match the expression until they find the first carriage return (\r). 
     // If you use ".*\r" (Greedy Expression), it will match until they find the last carriage return of the input. Thats why you matched ("&amp;st.directLink=on&amp;st.referenceName=makeuppro"), because the last "&amp" is after "makeuppro" . 
     // Here the correct pattern. 
     var pattern = "groupId=(?<id>[^\"\"]+?)&amp"; 

     // Match the desired part of the input. 
     var match = Regex.Match(xml, pattern); 

     // Verify the match sucess. 
     if (match.Success) 
     { 
      // Finally, use the group value to isolate desired value. 
      groupId = match.Groups["id"].Value; 
     } 

     return groupId; 
    } 

我希望它能幫助你!

真誠,