繁体   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