简体   繁体   中英

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.

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

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

string where why should be true

string where why is should be false because of is

string hello should be true

string hello bro should be false because of bro

Means string should only contains only the words 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
^(\\s*(hello|hi) )+$ eventually be prefixed by zero or more spaces,
^(\\s*(hello|hi)(\\s+ ))+$ and is suffixed by one or more spaces
^(\\s*(hello|hi)(\\s+|$))+$ or end of string.

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)}`)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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