📜  dart 计算字符串中的单词 - Dart (1)

📅  最后修改于: 2023-12-03 14:40:37.090000             🧑  作者: Mango

用 Dart 计算字符串中的单词

在 Dart 中,可以使用正则表达式来计算字符串中的单词。

以下代码片段演示如何使用正则表达式来计算字符串中的单词:

void main() {
  String str = "This is a sample string.";
  RegExp exp = RegExp(r"\w+");
  Iterable<RegExpMatch> matches = exp.allMatches(str);
  for (RegExpMatch match in matches) {
    print(match.group(0));
  }
}

在这个例子中,我们将字符串 "This is a sample string." 存储在变量 str 中。然后,我们定义了一个正则表达式对象 exp,该表达式可以匹配任何单词字符(字母、数字和下划线)。

我们使用 exp.allMatches() 方法将 exp 应用于 str,并返回匹配的结果。结果是一个可迭代对象 matches,我们可以使用 for-in 循环来遍历这个对象,并使用 match.group(0) 方法来获取每个匹配项的文本值。

输出结果如下:

This
is
a
sample
string

以上演示如何在 Dart 中计算字符串中的单词。