[英]Javascript regular expression to ignore a sequence of full-stops/dots
我正在嘗試計算 javascript 中字符串中的單詞數,但忽略字符串中任何位置包含字符“...”的單詞。 我知道一個“。” 可以在正則表達式中用作特殊字符,但我嘗試在下面打破它不起作用(函數的第 4 行)...
function countWords(s){
s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude start and end white-space
s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
s = s.replace(/\.\.\.$/,""); //exclude words ending in ...
return s.split(' ').length;
}
有誰知道我做錯了什么?
關於什么:
function countWords(s) {
return s.split(/\b(?:\w+(?:\.{3}|\u2026)|\W+)/).filter(Boolean).length;
}
此函數不使用多個替換,而是將字符串拆分為非單詞字符或后跟 3 個點(或省略號)的單詞。 filter(Boolean)
刪除空項目。
請注意,我所說的“單詞”是來自[A-Za-z0-9_]
一個或多個字符,如果您對某個單詞的定義不同,請解釋您在問題中究竟要尋找什么。
如果要算一個單詞,用撇號或連字符分隔的單詞,那么使用match
方法更容易:
return s.match(/\w+(?:['-]\w+)*\b(?!\.{3}|\u2026)/g).filter(Boolean).length;
通過這種方式,您可以准確地描述允許或不允許的內容。
這將選擇以“...”或“...”結尾的單詞
/\w+\s*[\.]{3}/g
https://regex101.com/r/uZ4cH9/1
就像上面案例中的“字符串...”或“字符串...”一樣。
測試字符串...
測試字符串...
/\\w+[\\.]{3}/g
https://regex101.com/r/yF2vV2/1
/\\S+[\\.]{3}/g
忽略字符串中任何位置包含字符“...”的單詞
...
s.replace(/...$/,""); //排除以...結尾的單詞
此正則表達式僅在出現在字符串末尾而不是任何地方時替換 '...'。
為了避免連接由 '...'(甚至只是 .)分隔的單詞:
function countWords(s){
s = s.replace(/\./g," ");
s = s.replace(/\n/," ");
s = s.replace(/[ ]{2,}/g," ");//2 or more space to 1
s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude start and end white-space
return s.split(' ').length;
}
嘗試使用 s.replace(/\\w*\\.\\.\\.(\\B|\\b)\\w*/,"");
代替
s.replace(/\\.\\.\\.$/,"");
這僅適用於僅包含一個 ... 子字符串的單詞。 對於,更多你需要修改這個
function count_words()
{
str1= document.getElementById("InputText").value;
//exclude start and end white-space
str1 = str1.replace(/(^\s*)|(\s*$)/gi,"");
//convert 2 or more spaces to 1
str1 = str1.replace(/[ ]{2,}/gi," ");
// exclude newline with a start spacing
str1 = str1.replace(/\n /,"\n");
document.getElementById("noofwords").value = str1.split(' ').length;
}
試試這個對我有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.