2014-11-03 19 views
1
>> s1 = "a=b" 
>> s2 = "a!=b" 

>> re.compile("SOMTHING").split(s1) 
>> # I expect ['a','1'] 

>> re.compile("SOMTHING").split(s2) 
>> # I expect ['a!=1'] and NOT ['a!,'1'] 

我想compile([^!]=).split(s2)但不工作,并给['','1']正则表达式:如何通过“=”而不是分裂

我怎样才能使这项工作“=!”?

回答

3

您可以使用negative lookbehind assertion

>>> s1 = "a=b" 
>>> s2 = "a!=b" 
>>> r = re.compile(r"(?<!!)=") 
>>> r.split(s1) 
['a', 'b'] 
>>> r.split(s2) 
['a!=b'] 

根据您的输入,您可能还需要向前看:

>>> s3 = "a==b" # I guess you wouldn't want to split that 
>>> r.split(s3) 
['a', '', 'b'] 
>>> r = re.compile(r"(?<![!=])=(?!=)") 
>>> r.split(s3) 
['a==b']