簡體   English   中英

正則表達式:只允許使用幾個單詞,每個單詞只能使用一次

[英]Regexp: Allow only use of a few words and only once per word

 var string; string = 'test'; console.log((/(test)+/g).test(string));//i want true string = 'another test'; console.log((/(test)+/g).test(string));//i want false string = 'test test'; console.log((/((\\w)+(\\w){3,}).*?\\1/g).test(string));//this work, but i want chose the words string = 'test test'; console.log((/((test)+(\\w)+).*?\\1/g).test(string));//this don't work, i can't chose 'test' 

如果有不可預測的詞,我想總是返回false。 我有一個單詞字符串,如果我在字符串中找到一個無法預測的單詞,我想要一個錯誤的單詞,所以我總是看到true,因為只有找到單詞時才進行控制。 對不起,英語,由谷歌翻譯。

據我所知,只有在完整的字符串由所需單詞組成的情況下,才需要返回true

這個正則表達式/^( ?test ?)+$/應該適合您。

這將強制字符串以單詞test開頭和結尾,並在單詞之間留一個空格。

所以,如果一個字符串中多次出現給定的字符串,您想匹配嗎? 您可以使用RegExp對象創建動態的regexp模式:

 var search = 'test'; var reg = new RegExp('('+search+').*?\\\\1','g'); console.log(reg.test('test')); // false console.log(reg.test('test test')); // true console.log(reg.test('another test')); // false console.log(reg.test('test another test')); //true 

暫無
暫無

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

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