【问题标题】:How to Regular expression to match only some words?如何正则表达式仅匹配某些单词?
【发布时间】:2017-07-26 07:34:57
【问题描述】:

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

我尝试了以下正则表达式,但它未能仅隔离这些单词,如果还存在任何其他单词,它将返回。

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

示例

字符串 hello world 应该是 false 因为 world

字符串 hello hi what 应该是真的

字符串 hello hi what word 应该是假的,因为 world

字符串 hello where 应该为真

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

字符串为什么应该是真的

字符串为什么是应该是假的,因为是

字符串 hello 应该为真

字符串 hello bro 应该是 false 因为 bro

意味着字符串应该只包含单词hello,hi,what,why,where

【问题讨论】:

  • 请提供一个示例,说明您的正则表达式的有效和无效输入。当我读到它时,我误解了你在问什么
  • 添加示例。请检查

标签: javascript regex


【解决方案1】:

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

^ $从字符串的开头到结尾应该有
^( )+$只有一个或多个
^( (hello|hi) )+$这个词,其中一个词可以
^(\s*(hello|hi) )+$最终以零为前缀或多个空格,
^(\s*(hello|hi)(\s+ ))+$ 并以一个或多个空格为后缀
^(\s*(hello|hi)(\s+|$))+$ 或字符串结尾。

【讨论】:

    【解决方案2】:

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

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

    工作代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      相关资源
      最近更新 更多