You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用IndexOf和Substring从HTML页面提取所有JPG结尾链接

从HTML中提取独立JPG链接的问题解决

问题描述

需要从HTML页面(包括类似https://something.com/my.jpg/a7gfefg/https://something.com/my2.jpg/sadsadsad64567546/https://something.com/my3.jpg的拼接链接)中提取所有以.jpg结尾的完整独立链接,每个链接单独提取。

原代码的错误点

  • 匹配后缀错误:代码中查找的是png后缀,完全不符合提取JPG链接的需求
  • Substring参数误用:line.Substring(index, index1)的第二个参数是截取长度,不是结束索引,会导致截取内容长度错误甚至超出范围
  • 未覆盖多链接场景:逐行用indexOf只能找到每行第一个匹配位置,无法处理同一行多个链接或拼接链接里的多个JPG链接
  • 结果未持久化:提取的result变量没有添加到links列表,最终无法获取到提取的链接

修正后的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Testing
{
    public partial class Form1 : Form
    {
        private List<string> links = new List<string>();
        string htmlCode;

        public Form1()
        {
            InitializeComponent();
            GetLinks();
        }

        private void GetLinks()
        {
            using (WebClient client = new WebClient())
            {
                htmlCode = client.DownloadString("https://test.com/my-site");
            }

            // 正则匹配所有以https://test.com开头、.jpg结尾的独立链接
            string pattern = @"https://test\.com.*?\.jpg";
            MatchCollection matches = Regex.Matches(htmlCode, pattern);

            foreach (Match match in matches)
            {
                links.Add(match.Value);
                // 可在此处添加输出或其他处理逻辑,比如:
                // Console.WriteLine(match.Value);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }
}

代码说明

  • 正则表达式逻辑:https://test\.com.*?\.jpg的匹配规则:
    • https://test\.com:精准匹配链接起始部分,转义.避免匹配任意字符
    • .*?:非贪婪匹配任意字符,确保找到最近的.jpg就停止,不会包含后续无关内容
    • \.jpg:匹配链接结尾后缀,保证提取的是JPG格式链接
  • 批量匹配处理:Regex.Matches一次性找出所有符合条件的链接,无需逐行遍历,覆盖单行多链接、拼接链接等所有场景
  • 结果保存:遍历匹配结果,将每个完整JPG链接添加到links列表,方便后续业务使用

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:12:34