匹配一个或多个数字的正则表达式

2024-10-03 19:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了这样的数据集(它以str形式从文件中打开):

MF8='out1mf8':'constant',[1944.37578865883]
MF9='out1mf9':'constant',[2147.79853787502]
MF10='out1mf10':'constant',[565.635908155949]
MF11='out1mf11':'constant',[0]
MF12='out1mf12':'constant',[0]

我需要将这些值放在括号中,因此创建的正则表达式:

^{pr2}$

并使用:

re.findall(outmfPattern, f)

mf = 9之前,它工作得很好。有人知道怎么处理这个吗?在


Tags: 数据形式括号constantstrout1mf9mf12out1mf8
1条回答
网友
1楼 · 发布于 2024-10-03 19:25:12

让我们分解一下您的regex out\dmf\d

  • out匹配序列'out'
  • \d匹配一个数字
  • mf匹配序列'mf'
  • \d匹配一个数字

如果您想匹配out1mf11,那么需要在末尾查找2数字。在

您可以使用out\dmf\d+,或者,如果您想在末尾只匹配1或2个数字,out\dmf\d{1,2}。在


In [373]: re.findall('out\dmf\d+', text)
Out[373]: ['out1mf8', 'out1mf9', 'out1mf10', 'out1mf11', 'out1mf12']

此外,如果要在这些搜索项中添加括号,则可能应该查看re.sub

^{pr2}$

re.sub将捕获的组替换为包含在parens中的相同组。在

相关问题 更多 >