简体   繁体   English

如何使正则表达式只匹配某些单词?

[英]How to Regular expression to match only some words?

I want to return true using javascript regex.test() method if the string contains only words from the list hello,hi,what,why,where and not any other words. 如果字符串仅包含列表中的单词hello,hi,what,why,where ,而不包含其他单词hello,hi,what,why,where我想使用javascript regex.test()方法返回true。

I tried the following regex but it failed to isolate only those words, and would return if any other words were also present. 我尝试了以下正则表达式,但它未能仅隔离那些单词,如果还存在其他单词,它将返回。

/(hello)|(hi)|(what)|(why)|(where)/gi.test(string)

Examples 例子

string hello world should be false because of world 字符串hello world应该因为world而为假

string hello hi what should be true 字符串你好你应该是什么

string hello hi what word should be false because of world 字符串你好你好,什么词应该是错误的,因为世界

string hello where should be true 字符串你好,哪里应该是真的

string where is should be false because of is 字符串where应当为false的原因

string where why should be true 为何正确的字符串

string where why is should be false because of is 为何为 false的字符串,原因

string hello should be true 字符串你好应该是真的

string hello bro should be false because of bro 字符串hello bro应该是错误的,因为bro

Means string should only contains only the words hello,hi,what,why,where 表示字符串仅应包含单词hello,hi,what,why,where

 function test1 ( str ) { return /^(\\s*(hello|hi|what|why|where)(\\s+|$))+$/i.test( str ); } console.log( test1("Hello where what") ); // true console.log( test1("Hello there") ); // false 

^ $ From start to end of string there should be ^ $从字符串的开始到结尾应该有
^( )+$ only one or more of ^( )+$仅以下一项或多项
^( (hello|hi) )+$ this words, where a word can ^( (hello|hi) )+$这个单词,其中一个单词可以
^(\\s*(hello|hi) )+$ eventually be prefixed by zero or more spaces, ^(\\s*(hello|hi) )+$最终以零个或多个空格为前缀,
^(\\s*(hello|hi)(\\s+ ))+$ and is suffixed by one or more spaces ^(\\s*(hello|hi)(\\s+ ))+$后缀一个或多个空格
^(\\s*(hello|hi)(\\s+|$))+$ or end of string. ^(\\s*(hello|hi)(\\s+|$))+$或字符串结尾。

You need to duplicate the regex group that matches the valid words, because there has to be at least one, but possibly more, separated by spaces. 您需要复制与有效单词匹配的正则表达式组,因为必须至少有一个,但可能还要用空格隔开。

You also need to use the ^ and $ anchors to match the whole string. 您还需要使用^$锚点来匹配整个字符串。

Working code: 工作代码:

 const examples = ['hello world', 'hello hi what', 'hello hi what word', 'hello where', 'where is', 'where why', 'where why is', 'hello', 'hello bro']; const regex = /^(?:hello|hi|what|why|where)(?:\\s(?:hello|hi|what|why|where))*$/; examples.forEach(str => console.log(`string "${str}" should be ${regex.test(str)}`)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM