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

标签 python regex

我有一个这样的字符串

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

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

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

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

关于python - 从 Python 中的字符串中提取数字和大小信息(KB、MB 等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341000/

相关文章:

python - 将 Pandas DataFrame 写入 Excel : How to auto-adjust column widths

python - 在 SciKit-Learn 中使用 XGBoost 的交叉验证进行网格搜索和提前停止

c++ - 在 Arch Linux 中使用 c++ Boost 正则表达式库

python - Python 中已编译的正则表达式列表

python - Django 内部服务器错误而不是 404

python - 使用 scikit 限制线性回归预测值

python - 如何编写python表达式来过滤掉某些字符串

c# - 如何更改正则表达式?

python - 情感分析管道,使用特征选择时获取正确特征名称的问题

r - 基于同一数据框中列名部分匹配的子集列