简体   繁体   English

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

[英]Javascript Regex to check repeating words pattern

How to parse string no check is it in valid pattern? 如何解析字符串而不检查它是否处于有效模式?

  1. I need to find are there words AND or OR 我需要找到单词AND或OR
  2. I need to check are they surrounded by another words, but not AND or OR 我需要检查它们是否被其他字词包围,但不包括AND或OR

If it is valid i will build query. 如果有效,我将建立查询。

Examples: 例子:

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

Would you be fine with a non-regex solution? 使用非正则表达式解决方案可以吗?

Try this 尝试这个

 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 bc" ) ); 

isValid first split the string based on and and or , then checks if the returned array has an empty element or not. isValid首先根据分割字符串,然后检查返回的数组是否包含空元素。

Try this regex: 试试这个正则表达式:

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

Demo 演示版

Explanation: 说明:

  • ^ - Start of the String ^ -字符串的开头
  • (?!\\s*(?:and|or)) - Negative lookahead - makes sure that and or or are not present at the beginning of the string preceded by 0+ spaces (?!\\s*(?:and|or)) -负向超前-确保在开头0+的字符串开头不存在and or or
  • (?!.*(?:and|or)\\s*$) - Negative lookahead - makes sure that and or or are not present at the end of the string followed by 0+ spaces (?!.*(?:and|or)\\s*$) -负向超前-确保在字符串的末尾不存在andor ,后跟0+空格
  • (?!.*and\\s+or) - makes sure or does not follow immediately after and and 1+ spaces (?!.*and\\s+or) -确保在and和1+空格之后紧跟or不紧跟
  • (?!.*or\\s+and) - makes sure 'and' does not follow immediately after or and 1+ spaces (?!.*or\\s+and) -确保'and'不紧跟在or和1+空格之后
  • .+ - match anything but new line characters 。+-匹配除换行符以外的任何字符
  • $ - End of String $ -字符串结尾

Update: 更新:

在此处输入图片说明

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

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