【问题标题】:match a pattern in text and read it to different variables匹配文本中的模式并将其读取到不同的变量中
【发布时间】:2021-10-23 09:08:43
【问题描述】:

我有以下模式:<num1>-<num2> <char a-z>: <string>。例如1-3 z: zztop

我想将它们解析为n1=1, n2=3, c='z', s='zztop'

当然,我可以通过拆分轻松地做到这一点,但是在 Python 中是否有更紧凑的方法来做到这一点?

【问题讨论】:

    标签: python-3.x regex parsing


    【解决方案1】:

    re.finditer 与具有命名捕获组的正则表达式一起使用:

    inp = "1-3 z: zztop"
    r = re.compile('(?P<n1>[0-9]+)-(?P<n2>[0-9]+) (?P<c>\w+):\s*(?P<s>\w+)')
    output = [m.groupdict() for m in r.finditer(inp)]
    print(output)  # [{'n1': '1', 'n2': '3', 'c': 'z', 's': 'zztop'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多