在 Dart 中将字符串拆分为单词、标点符号和空格的数组
我正在尝试复制此页面上提到的方法:
在 JavaScript 中将字符串拆分为单词、标点符号和空格的数组
例如:
var text = "I like grumpy cats. Do you?";
console.log(
text.match(/\w+|\s+|[^\s\w]+/g)
)
返回:
[
"I",
" ",
"like",
" ",
"grumpy",
" ",
"cats",
".",
" ",
"Do",
" ",
"you",
"?"
]
但我使用的不是 Javascript,而是 Dart。我很难找到在 Dart 中如何工作的示例,尤其是在格式化正则表达式方面。
我已经尝试过此操作,但它没有返回标点符号和空格:
dynamic textToWords(String text) {
// Get an array of words, spaces, and punctuation for a given string of text.
var re = RegExp(r"\w+|\s+|[^\s\w]+g");
final words = text != null
? re.allMatches(text != null ? text : '').map((m) => m.group(0)).toList()
: [];
return words;
}
感谢任何帮助。
I'm trying to replicate a method mentioned on this page:
Split a string into an array of words, punctuation and spaces in JavaScript
For example:
var text = "I like grumpy cats. Do you?";
console.log(
text.match(/\w+|\s+|[^\s\w]+/g)
)
Returns:
[
"I",
" ",
"like",
" ",
"grumpy",
" ",
"cats",
".",
" ",
"Do",
" ",
"you",
"?"
]
But instead of Javascript, I'm using Dart. I'm having a hard time finding examples of how this would work in Dart, especially in formatting the regex.
I've tried this, but it's not returning the punctuation and spaces:
dynamic textToWords(String text) {
// Get an array of words, spaces, and punctuation for a given string of text.
var re = RegExp(r"\w+|\s+|[^\s\w]+g");
final words = text != null
? re.allMatches(text != null ? text : '').map((m) => m.group(0)).toList()
: [];
return words;
}
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从
RegExp
末尾删除g
。而且
text
永远不会为 null,因为您将其声明为String
,因此不需要这些 null 检查。Remove the
g
from the end of yourRegExp
.Also
text
will never be null since you declared it as aString
, so there is no need for these null checks.