Skip to main content
 首页 » 编程设计

Python 正则表达式搜索内部带逗号的 float

2024年12月31日31mfryf

我有这样的字符串:

a = "opening Balance 25,07,708.33 |Fixed Assets (Furniture)" 
b = "|Add: income during the Yr, 5,95,719.92 |0/Balance 55,221.00" 
c = "|Les:- Dep@10% 5,522.00 49,699.00" 

我只想从列表中的字符串中获取 float 值,例如:

a_l = ["25,07,708.33"] 
b_l = ["5,95,719.92" , "55,221.00"] 
c_l = ["5,522.00" , "49,699.00"] 

我在 python 中使用正则表达式尝试这段代码:

import re 
a_l = a[re.search(r'((\d+\,+)+\d+\.\d{2})', a).span()[0]:re.search(r'((\d+\,+)+\d+\.\d{2})', a).span()[1]] 
# same for b_l, c_l 

我得到的输出如下:

a_l = '25,07,708.33' 
b_l = '5,95,719.92' 
c_l = '5,522.00' 

它只检测第一次出现这种情况,然后忽略其他情况。在不替换其中的逗号的情况下搜索 float 值的正确模式是什么?

请您参考如下方法:

你可以简单地做

b = "|Add: income during the Yr, 5,95,719.92 |0/Balance 55,221.00" 
import re 
a_l = re.findall(r'((?:\d+,+)+\d+\.\d{2})', b) 
print a_l 

输出: ['5,95,719.92', '55,221.00']