Skip to main content
 首页 » 编程设计

python之从 Python 中的字符串中提取数字和大小信息(KB、MB 等)

2025年05月04日47mayingbao

我有一个这样的字符串

"44MB\n" (it can be anything ranging from 44mb, 44 MB, 44 kb, 44 B) 

我想将 44 和 MB 从上面的字符串中分离出来。我写了这段代码来提取数字

import re 
mystring = "44MB\n" 
re.findall(r'\d+', mystring) 

为了提取大小,我想避免使用 if 语句,例如

if "kb" mystring.lower():  
    # Do stuffs 
if ....... 

如何使用正则表达式提取尺寸信息

请您参考如下方法:

这个脚本:

import re 
 
 
test_string = '44.5MB\n12b\n6.5GB\n12pb' 
 
regex = re.compile(r'(\d+(?:\.\d+)?)\s*([kmgtp]?b)', re.IGNORECASE) 
 
order = ['b', 'kb', 'mb', 'gb', 'tb', 'pb'] 
 
for value, unit in regex.findall(test_string): 
    print(int(float(value) * (1024**order.index(unit.lower())))) 

将打印:

46661632 
12 
6979321856 
13510798882111488 

它以字节为单位找到的大小。