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

在C#中如何从URL字符串中提取指定的可变数字部分

C# 提取URL中指定数字段的实现方案

你的URL结构为[域名]/app/[目标数字段]/[其他路径]的前提下,可通过以下两种可靠方式实现需求:

方法一:Uri类+路径拆分(性能更高,适合结构固定场景)

该方案不需要引入正则依赖,逻辑清晰,运行效率更高:

// 输入待处理URL
string url = "https://example.com/app/1095600/example2234";
Uri uri = new Uri(url);
// 处理路径段,去除收尾的斜杠
List<string> pathSegments = uri.Segments.Select(segment => segment.Trim('/')).ToList();

// 定位app路径段的位置
int appSegmentIndex = pathSegments.FindIndex(s => s.Equals("app", StringComparison.OrdinalIgnoreCase));
if (appSegmentIndex != -1 && appSegmentIndex + 1 < pathSegments.Count)
{
    string targetValue = pathSegments[appSegmentIndex + 1];
    // 验证是否为长度≥3的纯数字
    if (targetValue.Length >= 3 && long.TryParse(targetValue, out _))
    {
        // 提取结果可直接使用
        Console.WriteLine($"提取到的数字段:{targetValue}");
    }
}

方法二:正则表达式(灵活度更高,适合结构有小幅变化场景)

该方案不需要严格依赖路径段的索引顺序,适配性更强:

using System.Text.RegularExpressions;

string url = "https://example.com/app/1095600/example2234";
// 匹配/app/后紧跟的3位及以上纯数字段
Match matchResult = Regex.Match(url, @"/app/(\d{3,})/");
if (matchResult.Success)
{
    string targetValue = matchResult.Groups[1].Value;
    Console.WriteLine($"提取到的数字段:{targetValue}");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:24:01