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

如何从JSON文件特定行提取指定路径中的随机数字串并清理行内容?

提取特定URL中的随机数字串并清理目标行内容(C#实现)

看起来你已经搞定了目标行的定位,接下来只需要两步:先清理行里的多余字符,再精准提取中间的数字串就行,我给你整理了两种靠谱的实现方式:

第一步:清理目标行的冗余内容

你提到行首有空白、行尾带;},结合JSON格式推测行内容大概率被引号包裹,用这几步就能清理干净:

  • 用Trim()去掉首尾所有空白字符
  • 用TrimEnd(';', '}')切掉行尾的;}
  • 用Trim('"')去掉前后的引号(如果存在的话)

第二步:提取中间的随机数字串

这里有两种方法,按需选择:

方法一:正则表达式(精准匹配,避免无关结果)

因为目标串固定在/models/和/textures?optimized=1之间,且示例中的串是十六进制格式(a-f+数字),可以写一个精准的正则,只匹配符合这个结构的内容,不会误抓其他结果:

using System.Text.RegularExpressions;

List<string> found = new List<string>();
string line;
using (StreamReader file = new StreamReader(Application.StartupPath + "\\textures.json"))
{
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains("textures?optimized=1"))
        {
            // 清理行内容
            string cleanedLine = line.Trim();
            cleanedLine = cleanedLine.TrimEnd(';', '}');
            cleanedLine = cleanedLine.Trim('"');
            
            // 用正则提取目标串
            Regex regex = new Regex(@"\/models\/([a-f0-9]+)\/textures\?optimized=1");
            Match match = regex.Match(cleanedLine);
            if (match.Success)
            {
                string targetId = match.Groups[1].Value;
                found.Add(targetId);
            }
        }
    }
}

如果你的数字串可能包含十六进制外的其他字符,把正则里的[a-f0-9]+改成[^/]+即可,它表示匹配除了斜杠之外的所有字符,兼容性更强。

方法二:字符串分割(结构固定时更简单)

如果URL的结构永远是/i/models/[目标串]/textures?optimized=1,用字符串分割更直观,不需要依赖正则:

List<string> found = new List<string>();
string line;
using (StreamReader file = new StreamReader(Application.StartupPath + "\\textures.json"))
{
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains("textures?optimized=1"))
        {
            // 清理行内容
            string cleanedLine = line.Trim();
            cleanedLine = cleanedLine.TrimEnd(';', '}');
            cleanedLine = cleanedLine.Trim('"');
            
            // 分割提取目标串
            string[] afterModels = cleanedLine.Split(new string[] { "/models/" }, StringSplitOptions.None);
            if (afterModels.Length >= 2)
            {
                string[] beforeTextures = afterModels[1].Split(new string[] { "/textures" }, StringSplitOptions.None);
                if (beforeTextures.Length >= 1)
                {
                    found.Add(beforeTextures[0]);
                }
            }
        }
    }
}

这样处理后,found列表里就会存储所有你需要的随机数字串啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:28:08