如何在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
相关产品推荐
相关产品推荐

