簡體   English   中英

使用 regEx 匹配句子中字符串的單個出現

[英]Match a single occurrence of a string in a sentence using regEx

如果一句話說

“你好你好”

測試應該返回false,但如果它像

“你好約翰”

它返回真。

我以為這就是我要做的全部/(hello){1}/

一個簡單的解決方案,它不會使正則表達式復雜化,但會計算給定字符串中的匹配數:

function isValid(str) {
   return (str.match(/hello/gi) || []).length === 1;
}

此 RegEx 將匹配任何重復的單詞:

(\b\w+\b).+\1

解釋:

來自Regexper.com 正則表達式

代碼

要檢查字符串不包含匹配項:

!("testing testing 1 2 3...".match(/(\b\w+\b).+\1/)) #=> false
!("testing 1 2 3...".match(/(\b\w+\b).+\1/)) #=> true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM