你应该用它split
来解决这个问题。
findall
将适用于任何有效的字符串。不幸的是,它也适用于任何无效的字符串。如果那是您想要的,那很好;但可能你想知道是否有错误。
例子:
>>> import re
>>> digits = re.compile("\d+")
>>> digits.findall("52345:54325432:555:443:3:33")
['52345', '54325432', '555', '443', '3', '33']
>>> digits.findall("52345:54325.432:555:443:3:33")
['52345', '54325', '432', '555', '443', '3', '33']
>>> digits.findall(""There are 2 numbers and 53 characters in this string."")
['2', '53']
当然,如果您确定只使用该re
模块,您可以先匹配然后拆分:
>>> valid = re.compile("(?:\d+:)*\d+$")
>>> digits = re.compile("\d+")
>>> s = "52345:54325432:555:443:3:33"
>>> digits.findall(s) if valid.match(s) else []
相比之下:
>>> [int(n) for n in "52345:54325432:555:443:3:33".split(":")]
[52345, 54325432, 555, 443, 3, 33]
>>> [int(n) for n in "52345:54325.432:555:443:3:33".split(":")]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '54325.432'
>>> [int(n)
... for n in "There are 2 numbers and 53 characters in this string.".split(":")]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10:
'There are 2 numbers and 53 characters in this string.'