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

Flutter中如何去除字符串特殊符号并在Chips中展示纯单词内容?

Flutter 字符串清理与 Chips 组件展示方案

一、字符串特殊符号清理

通过正则表达式匹配并移除所有非目标字符,仅保留单词和空格,再处理多余空格:

String cleanText(String input) {
  // 移除所有非字母、非空格的字符(如需保留数字,可改为 [^a-zA-Z0-9\s])
  String cleaned = input.replaceAll(RegExp(r'[^a-zA-Z\s]'), '');
  // 合并连续空格并去除首尾空格
  return cleaned.replaceAll(RegExp(r'\s+'), ' ').trim();
}

调用示例:

String rawText = "Hello! This is a test, with special@#$ symbols. Let's go!";
String processedText = cleanText(rawText);
// 输出:"Hello This is a test with special symbols Lets go"

二、在 Chips 组件中展示处理后的单词

将清理后的字符串分割为单词列表,通过 Wrap 组件实现流式 Chips 布局:

完整示例 Widget:

class WordChipsScreen extends StatelessWidget {
  final String rawContent = "Hello! This is a test, with special@#$ symbols. Let's go!";

  String cleanText(String input) {
    String cleaned = input.replaceAll(RegExp(r'[^a-zA-Z\s]'), '');
    return cleaned.replaceAll(RegExp(r'\s+'), ' ').trim();
  }

  @override
  Widget build(BuildContext context) {
    String processedText = cleanText(rawContent);
    List<String> wordList = processedText.split(' ');

    return Scaffold(
      appBar: AppBar(title: const Text("单词标签展示")),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Wrap(
          spacing: 8.0, // Chips 横向间距
          runSpacing: 4.0, // Chips 纵向间距
          children: wordList.map((word) {
            return Chip(
              label: Text(word),
              backgroundColor: Colors.grey[200],
              // 可选:添加删除按钮
              // onDeleted: () => {/* 处理删除逻辑 */},
            );
          }).toList(),
        ),
      ),
    );
  }
}

说明

  • 正则可按需调整:如果需要保留下划线或数字,修改正则表达式的匹配范围即可;
  • Wrap 组件自动适配屏幕宽度,实现 Chips 换行;
  • 可自定义 Chip 的样式(背景色、文字样式、删除按钮等)满足UI需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:44:16