开发者

python simple regex help

Hi first time regex user here. Just trying to figure out some regex but need some help.

I have a text file with the following items:

10:67 12:12 01:50 23:60 23:50

And I'm trying to get a list of the valid times so the output should be:

['12:12', '01:50', '23:50']

Here is my code:

import re
inFile = open("text.txt")
text = inFile.read()
pattern = re.findall('([01]\d|2[0-3]):[0-5]\d', t开发者_如何学编程ext)
print pattern

My output is:

['12', '01', '23']

Any help figuring out whats wrong? Thanks!!!


Python apparently only prints the first group (that's ([01]\d|2[0-3]) in your case). If you make a non-capturing group ((?: ... )) of it, you should see the desired result:

text = '10:67 12:12 01:50 23:60 23:50'
pattern = re.findall('(?:[01]\d|2[0-3]):[0-5]\d', text)
print pattern

displays:

['12:12', '01:50', '23:50']

More info on (non-) capturing groups: http://www.regular-expressions.info/brackets.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜