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

Flutter技术问题:如何将含ID的文本替换为对应ID的标题?

Flutter中哈希标签ID替换为标题的实现方法

步骤1:提取文本中的ID

使用正则表达式匹配 #:hashtag/数字 格式的内容,提取其中的ID:

String originalText = '''Forecaster Strongly disagree 

Something else is going to happen

Example:-

#:hashtag/424 
#:hashtag/2818''';

// 定义正则匹配规则
RegExp hashtagRegex = RegExp(r'#:hashtag/(\d+)');
// 获取所有匹配结果
Iterable<Match> matches = hashtagRegex.allMatches(originalText);
// 提取ID列表
List<String> ids = matches.map((match) => match.group(1)!).toList();

步骤2:获取ID对应的标题

根据业务场景,你可以用本地映射或者异步请求API获取标题:

// 本地映射示例
Map<String, String> idToTitle = {
  "424": "Title1",
  "2818": "Title2",
};

// 异步API请求示例(模拟)
Future<Map<String, String>> fetchTitles(List<String> ids) async {
  // 替换为实际的API请求逻辑
  await Future.delayed(const Duration(milliseconds: 500));
  return {
    "424": "Title1",
    "2818": "Title2",
  };
}

步骤3:替换文本中的哈希标签

遍历匹配结果,将原标签替换为带标题的格式:

// 同步替换
String processedText = originalText;
for (var match in matches) {
  String id = match.group(1)!;
  // 找不到标题时保留原格式,避免显示异常
  String title = idToTitle[id] ?? match.group(0)!;
  processedText = processedText.replaceFirst(match.group(0)!, "#$title");
}

// 异步替换(适用于API获取标题的场景)
Future<String> processTextAsync() async {
  Map<String, String> titleMap = await fetchTitles(ids);
  String text = originalText;
  for (var match in matches) {
    String id = match.group(1)!;
    String title = titleMap[id] ?? match.group(0)!;
    text = text.replaceFirst(match.group(0)!, "#$title");
  }
  return text;
}

执行同步替换后,processedText 的内容为:

Forecaster Strongly disagree 

Something else is going to happen

Example:-

#Title1 
#Title2

内容的提问来源于stack exchange,提问作者who-aditya-nawandar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:00:53