2014-11-03 53 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']