简体   繁体   English

用于检查字符串中的单词的正则表达式仅用空格分隔,而不用_AND _ / _ OR_ python分隔

[英]Regex to check words in string are separated only by spaces and not by _AND_/_OR_ python

Regex in python to check if words in string are not separated by words like _AND_,_OR_ and only separated by spaces. python中的正则表达式,用于检查字符串中的单词是否_AND_,_OR_类的单词_AND_,_OR_而仅由空格分隔。

meaning of underscore here is space after and before word AND/OR. 下划线的含义是AND / OR字词前后的空格。

For eg: 例如:

1.) foo AND bar - should fail 1.) foo AND bar应该失败

2.) foo AND bar cafe - should fail because it has _AND_ 2.) foo AND bar cafe _AND_应该失败,因为它有_AND_

3.) foo AND bar OR cafe foobar baz - fail because it has _AND_/_OR_ in it 3.) foo AND bar OR cafe foobar baz _AND_/_OR_失败,因为其中包含_AND_/_OR_

4.) foo bar baz foobar - pass because it is separated only spaces and no _AND_/_OR_ 4.) foo bar baz foobar _AND_/_OR_通过,因为它仅由空格分隔,没有_AND_/_OR_

5.) fooANDbarOR bar - pass because it is not separated by _AND_/_OR_ . 5.) fooANDbarOR bar传递,因为它不由_AND_/_OR_

I know how to check if words are separated by _AND_/_OR_ -> 我知道如何检查单词是否由_AND_/_OR_ ->

\W(:?AND|OR)\W

I know how to check if words are separated by spaces -> 我知道如何检查单词是否用空格隔开->

\w\s

But i don't know how to combine both these things such that strings are separated only by spaces and not by _AND_/_OR_ 但是我不知道如何将这两种东西结合起来,使得字符串仅用空格分隔,而不用_AND_/_OR_

You can use 您可以使用

^(?:[\w ](?! (AND|OR) ))+$

The repeated [\\w ] ensures that all characters are either word characters or spaces, nothing else. 重复的[\\w ]可确保所有字符均为文字字符或空格,仅此而已。 After each character, negative lookahead for (AND|OR) to ensure that neither of those are standalone words: 在每个字符之后,对(AND|OR)进行否定的前瞻,以确保这两个都不是独立的单词:

https://regex101.com/r/LyRr5U/2 https://regex101.com/r/LyRr5U/2

If you also want to exclude standalone words, add positive lookahead to the beginning of the regex to ensure that there are some word characters separated by spaces somewhere in the string: 如果您还想排除独立的单词,请在正则表达式的开头添加正向前行,以确保在字符串中的某些单词字符之间用空格分隔:

^(?=.*\w +\w)(?:[\w ](?! (AND|OR) ))+$

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

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