YSMull
<-- algorithm



原题链接

这道题直接正则做的,当做一个正则表达式的练习题

let countValidWords = function (sentence) {
    let words = sentence.split(' ').filter(a => a);
    let count = 0;
    words.forEach(w => {
        if (/^([a-z]+(-[a-z]+)?)?[.!,]?$/g.test(w)) count++;
    });
    return count;
};

看了解答区,还可以这样写正则,感觉好理解一点:

([a-z]*|([a-z]+-[a-z]+))[!.,]?