.*?
是
非贪婪
也就是说,它将匹配最小的子字符串,您需要
贪婪的
版本,即
.*
(匹配最长的子字符串)对于后者:
In [1143]: a = '#232 - Hello There'
In [1144]: re.findall('#(.*?) - (.*?)', a)
Out[1144]: [('232', '')]
In [1145]: re.findall('#(.*?) - (.*)', a)
Out[1145]: [('232', 'Hello There')]
但你应该用
str
处理此类简单案例的方法,例如使用
str.split
打开拆分
-
以下内容:
In [1146]: a.split(' - ')
Out[1146]: ['#232', 'Hello There']
与
str.partition
在
-
切片:
In [1147]: a.partition(' - ')[::2]
Out[1147]: ('#232', 'Hello There')