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
相关产品推荐
相关产品推荐

