Javascript正则表达式检查重复单词模式

时间:2017-09-21 05:43:09

标签: javascript regex

如何解析字符串no check是否为有效模式?

  1. 我需要找到单词AND或OR
  2. 我需要检查他们是否被其他单词包围,但不是AND或OR
  3. 如果它有效,我将构建查询。

    示例:

    a and b or c -> valid
    a and or b   -> invalid
    a or and b   -> invalid
    a or b       -> valid
    a and b or   -> invalid
    and b or c   -> invalid
    

2 个答案:

答案 0 :(得分:1)

你是否可以使用非正则表达式解决方案?

试试这个



function isValid( str )
{
  return str.split(/\s*and\s*|\s*or\s*/g).filter( function(item){
     return item.length == 0 ;
  }).length == 0;
}

console.log( isValid( "a and b or c" ) );
console.log( isValid( "a and or b" ) );
console.log( isValid( "a or and b" ) );
console.log( isValid( "a or b" ) );
console.log( isValid( "a and b or" ) );
console.log( isValid( "and b or c" ) );

console.log( isValid( "a and b c" ) ); 




isValid首先根据以及拆分字符串,然后检查返回的数组是否包含空元素。

答案 1 :(得分:1)

试试这个正则表达式:

^(?=.*(?:and|or).*$)(?!(?:"\s*")*\s*(?:and|or))(?!.*(?:and|or)\s*(?:"\s*")*$)(?!.*and\s+or)(?!.*or\s+and).*$

Demo

<强>解释

  • ^ - 字符串的开头
  • (?!\s*(?:and|or)) - 否定前瞻 - 确保{0}空格前面的字符串开头不存在andor
  • (?!.*(?:and|or)\s*$) - 否定前瞻 - 确保字符串末尾不存在andor,后跟0 +空格
  • (?!.*and\s+or) - 确保在or和1 +空格后不立即and
  • (?!.*or\s+and) - 确保在or和1 +空格后不立即执行'和'
  • 。+ - 匹配除新换行符之外的任何内容
  • $ - 字符串结尾

更新

enter image description here

相关问题