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

如何用正则表达式提取Twitter URL中status后的数字?

从Twitter URL提取status后的数字ID

问题分析

你之前的代码仅截取了status开始的部分,没有过滤后续的非数字内容(比如URL参数),所以无法得到纯数字的状态ID。以下是三种可靠的实现方法:


方法1:正则表达式(推荐)

通过正则匹配/status/后的连续数字序列,无论URL后是否带参数都能准确提取:

final url = _controller.text;
// 匹配/status/后面的所有数字
RegExp statusReg = RegExp(r'/status/(\d+)');
Match? matchResult = statusReg.firstMatch(url);

if (matchResult != null) {
  String statusId = matchResult.group(1)!;
  // statusId即为目标数字,示例输出:1596714080345415681
}

方法2:字符串分割处理

先定位/status/的位置,再截取后续内容并过滤非数字字符:

final url = _controller.text;
int statusPos = url.indexOf('/status/');

if (statusPos != -1) {
  // 跳过'/status/'这8个字符,取后面的内容
  String afterStatus = url.substring(statusPos + 8);
  // 找到第一个非数字的位置,截取之前的部分
  int nonDigitPos = afterStatus.indexOf(RegExp(r'[^0-9]'));
  String statusId = nonDigitPos == -1 ? afterStatus : afterStatus.substring(0, nonDigitPos);
}

方法3:URL解析类处理

利用语言自带的URL解析工具拆分路径段,直接获取status后的下一段内容:

final url = _controller.text;
Uri twitterUri = Uri.parse(url);
List<String> pathParts = twitterUri.pathSegments;

int statusIndex = pathParts.indexOf('status');
if (statusIndex != -1 && statusIndex + 1 < pathParts.length) {
  String statusId = pathParts[statusIndex + 1];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:05:27