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

如何在Flutter/Dart中拆分多语言字符串为单词?

解决Dart/Flutter正则匹配多语言字母单词的问题

我有如下字符串:

I like grumpy cats. Do you? ффффф ыыыыы ইউটিউব থেকে

若在正则表达式中使用\w,则只能提取拉丁字母组成的单词:

final text = "I like grumpy cats. Do you? ффффф ыыыыы ইউটিউব থেকে";
RegExp re = RegExp(r"\w+");
List<String> words = [];
for (Match match in re.allMatches(text)) {
  words.add(match.group(0)!);
}
print(words);

输出结果:

[I, like, grumpy, cats, Do, you]

但我需要的结果是:

[I, like, grumpy, cats, Do, you, ффффф, ыыыыы, ইউটিউব, থেকে]

已知\p{L}表示“任意语言的任意类型字母”,但默认在Dart/Flutter中无法生效,原因是Dart的正则表达式默认未启用Unicode属性支持,只需在创建RegExp时添加unicode: true参数即可解决。

修改后的代码如下:

final text = "I like grumpy cats. Do you? ффффф ыыыыы ইউটিউব থেকে";
RegExp re = RegExp(r"\p{L}+", unicode: true); // 开启Unicode支持
List<String> words = [];
for (Match match in re.allMatches(text)) {
  words.add(match.group(0)!);
}
print(words);

此时输出结果会符合预期:

[I, like, grumpy, cats, Do, you, ффффф, ыыыыы, ইউটিউব, থেকে]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 06:27:41