在字符串中查找 hrefs 值

Find hrefs value in string

如何从所有 href 中检索所有 url 我不想使用 HTML Agility Pack 或类似的 - 必须是干净的代码并且非常短。

        HttpClient client = new HttpClient();
        static async Task Main(string[] args)
        {
            Program program = new Program();
            await program.GetTodoItems();
            await program.Function();
            Console.WriteLine("Hello Word!");
        }

        private async Task GetTodoItems()
        {
            string ResponseHtml = await client.GetStringAsync("https://example.com");

            var LinkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            foreach (Match m in LinkParser.Matches(ResponseHtml))
            {
                Console.WriteLine(m.Value);
            }
        }

我希望干净的 url 不会翻倍,并且仅适用于网站而不适用于脚本。此代码向我展示了一些带有额外标签和字符的 link,如下所示:

https://example.com/libs/jquery/1.11.2/jquery.min.js">

https://www.google-analytics.com/analytics.js','ga

围绕 "one or more not white space"

扩展捕获组
LinkParser = new Regex(@"\b(?<url>https?://\S+)['""]", RegexOptions.Compiled | RegexOptions.IgnoreCase);

然后使用

访问匹配集合
m.Groups["url"].Value

一个更简单的模式可能也很有效:\b(?<url>http.*?)['"]

这些都是非常原始的,我不保证它在所有情况下都有效。如果您的网址根本没有被引用,请考虑在末尾添加空格和右尖括号 class。你最好为此使用可靠的库 because ...