正则表达式:捕获没有整数部分的浮点数

问题描述 投票:0回答:3

我正在尝试使用正则表达式捕获字符串中没有整数部分的浮点数。例如:我有字符串:

The dimensions of the object-1 is: 1.4 meters wide, .5 meters long, 5.6 meters high
The dimensions of the object-2 is: .8 meters wide, .11 meters long, 0.6 meters high

我只想捕获没有整数部分的小数,并向它们添加前导零。所以我最终想要的输出是:

The dimensions of the object-1 is: 1.4 meters wide, 0.5 meters long, 5.6 meters high
The dimensions of the object-2 is: 0.8 meters wide, 0.11 meters long, 0.6 meters high

这是我到目前为止尝试过的:

(\d+)?\.(\d+)

此表达式捕获所有小数,例如:

1.4, .5, 5.6, .8, .11, 0.6

但我只需要捕获没有整数部分的小数:

.5, .8, .11

python regex floating-point expression leading-zero
3个回答
0
投票

使用负面回顾:

(?<!\d)(\.\d+)


0
投票

你可以做一个正则表达式替换负向后看一个数字。

  • 正则表达式 -
    (?<!\d)(\.\d+)
  • 替换 -
    0$1

Regex101 演示


0
投票

按照您的意愿去做似乎很奇怪。为什么不捕获所有小数并格式化它们?

print(f'{0.185:0.3f}') #0.185
print(f'{.185:0.3f}')  #0.185
© www.soinside.com 2019 - 2024. All rights reserved.