【发布时间】:2019-11-03 18:45:20
【问题描述】:
源字符串是:
# Python 3.4.3
s = r'abc123d, hello 3.1415926, this is my book'
这是我的模式:
pattern = r'-?[0-9]+(\\.[0-9]*)?|-?\\.[0-9]+'
但是,re.search 可以给我正确的结果:
m = re.search(pattern, s)
print(m) # output: <_sre.SRE_Match object; span=(3, 6), match='123'>
re.findall 只是转储一个空列表:
L = re.findall(pattern, s)
print(L) # output: ['', '', '']
为什么re.findall不能给我预期的名单:
['123', '3.1415926']
【问题讨论】:
-
将捕获组转为非捕获组。
-
@AvinashRaj,嗯..,如果我删除那个捕获组,即使 re.search 给我一个 None 结果
-
@stribizhev,不是,'3.1415926' 应该是结果中的浮点数
-
@O'Skywalker 尝试使用 puttern 像 -?\d?\.?\d+
-
一些在线网站可以帮助调试,例如texttoolkit.com/re.findall