【问题标题】:Regex fields extraction with python使用 python 提取正则表达式字段
【发布时间】:2011-04-30 20:06:15
【问题描述】:

我有一个这样的字符串:

字段1:值1 字段2:值2

字段可以有空格,即。 "field name:" 但 value 字段永远不会有。

在不事先知道字段名称的情况下,使用正则表达式将字段值对提取到数字组中的简单方法是什么?

我正在使用 python b

谢谢

【问题讨论】:

    标签: regex


    【解决方案1】:
    >>> subject = "field name 1:value1 field2:value2  field name3:value3"
    >>> d = { match.group(1): match.group(2)
    ...       for match in re.finditer(r"([^:]+):(\S+)\s*", subject)
    ...     }
    >>> d
    {'field name 1': 'value1', 'field2': 'value2', 'field name3': 'value3'}
    

    这是使用使用此正则表达式填充的字典理解:

    ([^:]+) # one or more characters except :  (--> group(1))
    :       # a literal :
    (\S+)   # one or more non-whitespace characters (--> group(2))
    \s*     # optional trailing whitespace (before the next match)
    

    【讨论】:

      【解决方案2】:

      你可以使用re.findall()做你想做的事:

      >>> data = "field1:value1 field2:value2 field with space:something"
      >>> re.findall(r'\s*([^:]+):(\S+)', data)
      [('field1', 'value1'), ('field2', 'value2'), ('field with space', 'something')]
      

      【讨论】:

        【解决方案3】:

        大概是这样的吧?

        ([^:]+:[^ ]*)*
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-02
          • 2012-12-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多