如何使用RegEx匹配以空格分隔的字符组?

时间:2018-08-28 01:24:10

标签: python regex python-2.7

我使用下面的RegEx来确定某个字符串是否用ANDOR分隔

\W(:?AND|OR)\

示例

Input:  ~abc[0|1] AND foo
Output: Match
Input:  ~secopssc{1,3} AND ~abc_d{3,4}
Output: Match

类似地,我想编写一个正则表达式,使其匹配所有仅用空格而不用ANDOR分隔的字符串。

我尝试了以下RegEx:

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

这在以下位置提供了正确的输出:

Input:  foo bar
Output: Match
// This is correct since "foo" and "bar" are separated by a space
Input:  foo
Output: No Match
// This is correct since nothing is separated by a space

但是在以下位置输出错误:

Input:  ~abc[0|1] foo
Output: No Match
// This is incorrect as both strings are separated by a space
Input:  ~secopssc{1,3} AND ~abc_d{3,4}
Output: No match
// This is incorrect as both strings are separated by a space

总结:一种检查长字符串是否仅由仅由空格分隔的字符组组成的方法。


有效字符串的示例:

foo{1,3} acb[1-2] a foo bar bar(qwer|qwyr)

(由于每个字符块之间都有空格,因此有效)

1 个答案:

答案 0 :(得分:0)

这解决了我的问题:

k = "foo{1,3} acb[1-2] AND a foo bar bar(qwer|qwyr)"
if not re.search(r'\W(:?AND|OR)\W', k) and k.strip().find(" ")!=-1:
      print "not separated by AND and OR but by space"
else:
      print "separated by AND/OR"