简体   繁体   English

正则表达式计算字符串中的单词总数

[英]Regex to count the total number of words in a string

The total number of words in this string is 11. But my code returns 13.此字符串中的总字数为 11。但我的代码返回 13。

var txt = "Helllo, my -! This is a great day to say helllo.\n\n\tHelllo! 2 3 4 23";
txt = txt.replace(/[0-9]/g, '');
var words_count = txt.match(/\S+/g).length;

\\S+ will match any non-space character, which will include substrings like -! \\S+将匹配任何非空格字符,其中包括像-! . . You might match sequences of non-space characters which also include at least one alphabetical character in them, with \\S*[az]\\S* :您可以匹配一系列非空格字符,其中至少包含一个字母字符,与\\S*[az]\\S*

 var txt = "Helllo, my -! This is a great day to sayhelllo.\\n\\n\\tHelllo! 2 3 4 23"; console.log(txt.match(/\\S*[az]\\S*/gi).length);

If you can count on what you want to count as a "word" to start with an alphabetical character, you can remove the leading \\S* .如果您可以指望要算作“单词”的内容以字母字符开头,则可以删除前导\\S*

If you want to make the trailing \\S* more restrictive, you could whitelist a list of permitted characters inside "words", like ' if you want:如果您想让尾随的\\S*更具限制性,您可以将“words”中允许的字符列表列入白名单,例如'如果需要:

 var txt = "Helllo, my -! This is a great day to sayhelllo.\\n\\n\\tHelllo! 2 3 4 23"; console.log(txt.match(/[az][a-z']*/gi).length);

(to add more characters to the whitelist, just expand the [a-z'] character set to whatever you need) (要将更多字符添加到白名单,只需将[a-z']字符集扩展为您需要的任何字符)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM