正则表达式匹配问题

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

为什么需要正则表达式?正确的正则表达式是什么?


6
我认为更健壮的方法是获取整个URL,然后使用HttpUtility.ParseQueryString之类的工具进行解析。 - Matthew
3个回答

4

您需要使用“勉强量词”来在第一个&amp处停止:-

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

0

试试这个:

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

我怀疑id中不会包含&字符。你的原始正则表达式是贪婪的,并且尝试匹配最长的字符串。


0

嗨 @user1895750 和 @Jared Harley,

你们对懒惰和贪婪表达式感到困惑了,看下面的代码。

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

希望对你有所帮助!

真诚地,


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接