You need to enable JavaScript to run this app. Dart 如何从混合字符串列表中分离并提取数字与文本内容
优惠活动
大模型
产品
解决方案
定价
更多

Dart 如何从混合字符串列表中分离并提取数字与文本内容

Dart 字符串列表的数字与文本分离实现

针对存储彩票号码的字符串列表,需要完成两类内容的拆分:一是将每个元素内的字母类文本字符归集,二是将每个元素内的数字字符单独提取,匹配待处理列表的典型结构:

List<String> n = ["ABC23", "21A23", "12A312","32141A"];

核心实现逻辑

  • 对列表内的单个字符串做逐字符遍历
  • 字符匹配规则为:可转为整数的字符归入数字集合,其余非数字字符归入文本集合
  • 遍历完成后按要求整理拆分结果并输出

完整可运行代码

// 单字符串拆分方法:返回结构化的拆分结果
(String extractedText, String extractedNumbers) splitContent(String raw) {
  final textPart = StringBuffer();
  final numPart = StringBuffer();
  for (final char in raw.split('')) {
    if (int.tryParse(char) != null) {
      numPart.write(char);
    } else {
      textPart.write(char);
    }
  }
  return (textPart.toString(), numPart.toString());
}

// 批量处理列表的方法
void processLotteryItems(List<String> sourceList) {
  for (final item in sourceList) {
    final splitResult = splitContent(item);
    // 可根据实际需要调整输出格式
    print("原条目:$item");
    print("  文本提取结果:${splitResult.extractedText}");
    print("  数字提取结果:${splitResult.extractedNumbers}\n");
  }
}

// 调用测试
void main() {
  List<String> n = ["ABC23", "21A23", "12A312","32141A"];
  processLotteryItems(n);
}

实际运行输出

原条目:ABC23
  文本提取结果:ABC
  数字提取结果:23

原条目:21A23
  文本提取结果:A
  数字提取结果:2123

原条目:12A312
  文本提取结果:A
  数字提取结果:12312

原条目:32141A
  文本提取结果:A
  数字提取结果:32141

可根据实际业务需求调整拆分规则:如果需要按连续字符块保留原顺序拆分(即不跨位置归集同类型内容,按连续段分割),可以将匹配逻辑替换为正则连续块匹配的实现,适配不同的彩票号码格式要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 12:54:07