[英]How to match character groups separated by spaces using RegEx?
我使用下面的RegEx来确定某些字符串是否用AND
或OR
分隔
\W(:?AND|OR)\
例子
Input: ~abc[0|1] AND foo Output: Match
Input: ~secopssc{1,3} AND ~abc_d{3,4} Output: Match
同样,我想编写一个正则表达式,使其匹配所有仅用空格而不用AND
或OR
分隔的字符串。
我尝试了以下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)
(有效,因为有空格分隔每个字符块)
这解决了我的问题:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.