python - 重新分组 : Is it possible to specify the value type?

标签 python regex

我有以下正则表达式来分解需要作为字典返回的子元素中的轮胎规范。它的数字元素需要作为 int 返回。

这是一个输入示例:

tyre_specs = '255/45W17'

所需的输出:
tyre_details = {'width': 255, 'profile': 45, 'rating': 'W', 'rim': 17}

我使用带有命名捕获的正则表达式模式捕获每个元素,它们与所需的输出字典键匹配。然后我使用 groupdict 来生成我的输出字典。但是,所有值都是字符串。所以我需要进一步处理相关值以将它们转换为 int。

我的功能,见下文,有效。但是我想知道是否有更好的方法来做到这一点。例如,有没有办法强制执行某些特定匹配组的类型?

如果不是,这种方法是“pythonic”吗?

这是我的功能
import re

def tyre_details(tyre_size):
    pattern = r'(?P<width>\d{3})\/(?P<profile>\d{2})(?P<rating>[A-Z]{1,2})(?P<rim>\d{2})'
    try:
        details = re.match(pattern, tyre_size).groupdict()
    except AttributeError:
        raise ValueError('Input does not conform to the usual tyre size nomenclature "Width/ProfileRatingRim"')

    int_keys = set('width profile rim'.split())
    for key in int_keys:
        details[key] = int(details[key])
    return details

编辑:
  • 添加了输入字符串不匹配时的处理异常。我将此作为值错误提出
  • 将要转换的键定义为集合而不是列表。
  • 删除了多余的 try/except 子句。
  • 最佳答案

    我会首先检查正则表达式是否匹配。如果是这样,那么 match.groups()可以直接解引用到变量中并用于构建最终的字典对象:

    import re
    
    def tyre_details(tyre_size):
        pattern  = r'(\d{3})/(\d{2})([A-Z]{1,2})(\d{2})'
        m = re.match(pattern, tyre_size)
        details = {}
        if m:
            width, profile, rating, rim = m.groups()
            details = {"width": int(width), "profile": int(profile), "rating": rating, "rim": int(rim)}
        return details
    
    tyre_specs = '255/45W17'
    print( tyre_details(tyre_specs) )
    # => {'width': 255, 'profile': 45, 'rating': 'W', 'rim': 17}
    

    Python demo

    使用这种方法不需要命名组,您也不需要任何 try/except或类型转换时的其他检查 strint因为有问题的组只匹配数字,请参阅 (\d{3}) , (\d{2})(\d{2}) .

    如果您需要完整的字符串匹配,请替换 re.matchre.fullmatch ,如果匹配可以出现在字符串中的任何位置,请使用 re.search .

    备注 /不是任何特殊的正则表达式元字符,不要在模式中对其进行转义。

    关于python - 重新分组 : Is it possible to specify the value type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58835942/

    相关文章:

    c# - 正在解析 '\L' - 无法识别的转义序列

    javascript - 尝试使用 subString 和 indexOf 从文本中获取 <img> 标签

    python - 根据索引值在列 'A' 中插入 Null

    python - 自动格式化python代码的工具?

    python - 如何从 numpy.datetime64 对象中获取一个小时、分钟等?

    javascript - 如何根据 JavaScript 中的白名单字符检查字符串?

    regex - 试图删除文档的第一列。

    python - Paho-MQTT错误结果码: 5

    python - 我如何将空格键绑定(bind)到 .onkeypress(function, space bar)

    php - 使用正则表达式将 URL 与模式匹配,返回键数组