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

Flutter/Dart中如何从URL字符串提取指定子串并存储?

在Dart中提取URL中的指定子串

针对你的需求,这里提供三种实用的实现方式:

方法一:利用Uri类解析URL

Dart的Uri类可以方便地解析URL结构,适合处理标准格式的URL:

String sample = "https://xyz-api.portal.com/";
Uri parsedUri = Uri.parse(sample);
String host = parsedUri.host; // 获取域名部分:"xyz-api.portal.com"
List<String> hostParts = host.split('.');
String result = hostParts.first; // 取第一个分隔部分:"xyz-api"

这种方法不需要依赖复杂的正则,对符合URL规范的输入兼容性最好。

方法二:使用正则表达式匹配

如果URL结构固定,正则表达式可以直接定位目标子串:

String sample = "https://xyz-api.portal.com/";
RegExp targetRegex = RegExp(r'https?://([^.]+)\.');
Match? matchResult = targetRegex.firstMatch(sample);
String result = matchResult?.group(1) ?? ""; // 提取捕获组内容,默认空字符串防止匹配失败

正则规则说明:https?://匹配http/https前缀,([^.]+)捕获第一个.之前的所有字符,也就是目标子串。

方法三:字符串索引截取

通过定位关键字符的索引直接截取,适合结构完全固定的场景:

String sample = "https://xyz-api.portal.com/";
// 找到"//"的结束位置
int startPos = sample.indexOf('//') + 2;
// 找到startPos之后第一个"."的位置
int endPos = sample.indexOf('.', startPos);
// 截取中间部分
String result = sample.substring(startPos, endPos);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:27:04