You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中提取与字符关联的数字及字符组合(如4GB)

解决方法

你的问题在于原正则表达式只匹配了数字部分,没有包含后面的单位以及可能存在的空格。调整正则表达式并处理匹配结果即可得到目标格式:

修正后的代码

import re

def extract_memory_units(string):
    # 匹配数字+可选空格+大写单位的组合
    raw_matches = re.findall(r'\d+\s*[A-Z]+', string)
    # 移除匹配结果中的空格,统一格式
    return [match.replace(' ', '') for match in raw_matches]

# 测试示例
string = "I have a cellphone with 4GB of ram and 64 GB of rom, My last computer had 4GB of ram and NASA only had 4KB when ... that's incredible"
print(extract_memory_units(string))  # 输出: ['4GB', '64GB', '4GB', '4KB']

关键说明

  • 正则表达式 r'\d+\s*[A-Z]+':
    • \d+:匹配1个或多个数字
    • \s*:匹配0个或多个空格(处理像"64 GB"这种带空格的情况)
    • [A-Z]+:匹配1个或多个大写字母(对应GB、KB这类单位)
  • 用列表推导式移除每个匹配结果中的空格,确保输出格式统一为"数字+单位"的无空格形式。

如果需要支持小写单位(比如gb、kb),可以把正则里的[A-Z]+改成[A-Za-z]+。

内容的提问来源于stack exchange,提问作者Gabriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 23:00:41