Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用正则表达式只匹配一些单词?_Javascript_Regex - Fatal编程技术网

Javascript 如何使用正则表达式只匹配一些单词?

Javascript 如何使用正则表达式只匹配一些单词?,javascript,regex,Javascript,Regex,如果字符串只包含列表中的单词而不包含任何其他单词,我想使用javascriptregex.test()方法返回true 我尝试了下面的正则表达式,但它无法仅分离出这些单词,如果还有其他单词,它将返回 /(hello)|(hi)|(what)|(why)|(where)/gi.test(string) 示例 字符串hello world应为false,因为world string您好,您好什么应该是真的 string你好,因为世界 字符串hello where应为true 字符串where is

如果字符串只包含列表中的单词而不包含任何其他单词,我想使用javascript
regex.test()
方法返回true

我尝试了下面的正则表达式,但它无法仅分离出这些单词,如果还有其他单词,它将返回

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

字符串hello world应为false,因为world

string您好,您好什么应该是真的

string你好,因为世界

字符串hello where应为true

字符串where is应为false,因为is

字符串其中why应为true

字符串where is应为false,因为is

字符串hello应为true

字符串hello bro应为false,因为bro


表示字符串应仅包含单词
您好,您好,什么,为什么,where

您需要复制与有效单词匹配的正则表达式组,因为必须至少有一个,但可能更多,由空格分隔

您还需要使用
^
$
锚来匹配整个字符串

工作代码:

const-examples=['hello-world','hello-hi-what','hello-hi-what's','hello-where's','where-why's','hello'hello-bro'];
const regex=/^(?:hello | hi | what | why | where)(?:\s(?:hello | hi | what | why | where))*$;
forEach(str=>console.log(`string“${str}”应该是${regex.test(str)}`)
函数test1(str){
return/^(\s*(hello | hi | what | why | where)(\s+|$)+$/i.test(str);
}
log(test1(“Hello where what”);//符合事实的

log(test1(“你好”);//false
请提供一个示例,说明您的正则表达式的有效输入和无效输入。当我读到它时,我误解了你的要求。请检查