首页 > 解决方案 > 如何使用正则表达式解决飞镖中的字数问题?

问题描述

做一个练习并试图得到所有的案例。

给定一个短语,计算该短语中每个单词的出现次数。

例如对于输入“olly olly in come free”

olly: 2

in: 1

come: 1

free: 1

到目前为止,我得到了什么:

Map<String, int> countWords(String words) {
var wordCount = Map<String, int>();

words.split(RegExp(r"\W")).forEach(
  (word) {
    wordCount.update(word.toLowerCase(), (value) => value + 1,
        ifAbsent: () => 1);
  },
);
return wordCount;}

所以它适用于简单的句子,但不适用于带有换行符、标点符号等的单词。

像这样的案例:

'one,\ntwo,\nthree'
'car: carpet as java: javascript!!&@\$%^&'
'Joe can\'t tell between \'large\' and large.'
'testing, 1, 2 testing'
'First: don\'t laugh. Then: don\'t cry.'
'Joe can\'t tell between app, apple and a.'
' multiple   whitespaces'
',\n,one,\n ,two \n \'three\''

我不擅长正则表达式,所以我不确定我错过了什么。请帮我找到解决办法,谢谢。

标签: regexdart

解决方案


而不是使用每个非单词字符拆分字符串,只需获取单词:

  var wordCount = {};
  for (var match in RegExp(r"\w+('\w+)?").allMatches('my& string with with symbols&%!1')) {
     wordCount.update(match.group(0).toLowerCase(), (value) => value + 1,
        ifAbsent: () => 1);
  }
  print(wordCount);

推荐阅读