[英]Regex to count the total number of words in a string
此字符串中的總字數為 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+
將匹配任何非空格字符,其中包括像-!
. 您可以匹配一系列非空格字符,其中至少包含一個字母字符,與\\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);
如果您可以指望要算作“單詞”的內容以字母字符開頭,則可以刪除前導\\S*
。
如果您想讓尾隨的\\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);
(要將更多字符添加到白名單,只需將[a-z']
字符集擴展為您需要的任何字符)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.