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"

groupID を取得する必要がありますoqxdtikenuenvnwuj0rxiwhgvyuvhjhzjrd

私は試した

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

しかし、結果は次のとおりでした。

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

なぜ、そして正しい正規表現は何ですか?

4

3 に答える 3

0

こんにちは@user1895750と@JaredHarley、

怠惰で貪欲な表現と混同しました。以下のコードを参照してください。

    /// <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;
    }

お役に立てば幸いです。

心から、

于 2012-12-13T16:05:08.027 に答える
0

これを試して:

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

IDに & 文字が含まれていないと思われます。元の正規表現は貪欲で、可能な限り長い文字列に一致させようとします。

于 2012-12-13T15:07:18.780 に答える