Python re.search()没有返回完整的组匹配

时间:2011-12-16 19:20:39

标签: python regex

import re

ip6 = "1234:0678:0000:0000:00cd:0000:0000:0000"
zeroes = re.search("(:?0000)+", ip6)
print zeroes.group(0)

:0000:0000

我正在尝试找到由冒号分隔的四个零的最长序列。该字符串包含三个这样的组的序列,但只打印了两个组。为什么呢?

编辑:正在打印:0000:0000,因为这是字符串中的第一个匹配 - 但我认为regexp总是寻找最长匹配?

3 个答案:

答案 0 :(得分:2)

更新的答案适用于Python 2.6:

p = re.compile('((:?0000)+)')
longestword = ""
for word in p.findall(ip6):
    if len(word[0])>len(longestword):
        longestword = word[0]
print longestword

答案 1 :(得分:2)

如果您没有停留在正则表达式上,可以使用itertools.groupby

from itertools import groupby

ip6 = "1234:0678:0000:0000:00cd:0000:0000:0000"

longest = 0
for section, elems in groupby(ip6.split(':')):
    if section == '0000':
        longest = len(list(elems))

print longest  # Prints '3', the number of times '0000' repeats the most.
               # you could, of course, generate a string of 0000:... from this

我确信这可以归结为更优雅的东西,但我认为这表明了这一点。

答案 2 :(得分:0)

我正在使用Python 2.7.3
如何使用re.finditer()

$ uname -r
3.2.0-4-amd64


#!/usr/bin/env python

import re

ip6 = "1234:0678:0000:0000:00cd:0000:0000:0000"

iters = re.finditer("(:?0000)+", ip6)
for match in iters:
    print 'match.group()  -> ',match.group()