首页 文章

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

提问于
浏览
0

我使用下面的RegEx来识别某些字符串是否由 ANDOR 分隔

\W(:?AND|OR)\

Examples

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))+$

This gave the correct output on:

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

But an incorrect output on:

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

To Summarise :检查长字符串是否仅包含仅由空格分隔的字符组的方法是什么 .


Example of a valid string:

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

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

1 回答

  • 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"
    

相关问题