找到由lazy,regex包围的字符串的可选中间部分

时间:2011-09-27 08:17:52

标签: python regex

我正在使用python和regex尝试提取字符串的可选中间部分。

>>> re.search(r'(.*?)(HELLO|BYE)?(.*?END)', r'qweHELLOsdfsEND').groups()
('', None, 'qweHELLOsdfsEND') #what I want is ('qwe', 'HELLO', 'sdfsEND')
>>> re.search(r'(.*?)(HELLO|BYE)?(.*?END)', r'qweBLAHsdfsEND').groups()
('', None, 'qweBLAHsdfsEND') #when the middle doesn't match. this is OK

如何提取可选中间?

注意:这是我的第一篇文章。

2 个答案:

答案 0 :(得分:2)

你的正则表达式失败了,因为第一部分很满意匹配空字符串,第二部分失败(这是可以的,因为它是可选的),所以第三部分捕获所有。解决方案:让第一部分与HELLOEND

匹配
>>> re.search(r'((?:(?!HELLO|BYE).)*)(HELLO|BYE)?(.*?END)', r'qweHELLOsdfsEND').groups()
('qwe', 'HELLO', 'sdfsEND')
>>> re.search(r'((?:(?!HELLO|BYE).)*)(HELLO|BYE)?(.*?END)', r'qweBLAHsdfsEND').groups()
('qweBLAHsdfs', None, 'END')

这可以接受吗?

<强>解释

(?:         # Try to match the following:
 (?!        # First assert that it's impossible to match
  HELLO|BYE # HELLO or BYE
 )          # at this point in the string.
 .          # If so, match any character.
)*          # Do this any number of times.

答案 1 :(得分:1)

你可以这样做:

try:
    re.search(r'(.*?)(HELLO|BYE)(.*?END)', r'qweHELLOsdfsEND').groups()
except AttributeError:
    print 'no match'