[英]Javascript Regex to check repeating words pattern
How to parse string no check is it in valid pattern? 如何解析字符串而不检查它是否处于有效模式?
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).*$
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*$)
-负向超前-确保在字符串的末尾不存在and
或or
,后跟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+空格之后 $
- End of String $
-字符串结尾 Update: 更新:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.