15 May 2012

python tips-正则表达式匹配不包含某些字符串




返回不包含AAA与BBB的字符串,不能使用[^AAA|BBB],需要使用断言.



举例:

返回所有以123开头,ab结尾,且中间不包含123和f12的字符串
>>> import re
>>> s = 'a123abvpd123d“p”f12ab123sabd123f1123abc'
>>> res = r'(123((?:(?!123|f12)[\s\S])*?)ab)'
>>> m = re.findall(res,s)
>>> result = [x[0] for x in m]
>>> print result
['123ab', '123sab', '123ab']
>>>

No comments :

Post a Comment