我正在嘗試復制此頁面上提到的方法:
在 JavaScript 中將字串拆分為單詞、標點和空格的陣列
例如:
var text = "I like grumpy cats. Do you?";
console.log(
text.match(/\w |\s |[^\s\w] /g)
)
回報:
[
"I",
" ",
"like",
" ",
"grumpy",
" ",
"cats",
".",
" ",
"Do",
" ",
"you",
"?"
]
但我使用的是 Dart 而不是 Javascript。我很難找到這在 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;
}
任何幫助表示贊賞。
uj5u.com熱心網友回復:
從. g_RegExp
由于您將其宣告為 a ,因此也text永遠不會為 null String,因此不需要這些 null 檢查。
List<String> 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] ");
final words = re.allMatches(text).map((m) => m.group(0) ?? '').toList();
return words;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436145.html
上一篇:如果數字以javascript開頭,如何對字串進行切片
下一篇:如何使用模式從字串中獲取特定資料
