0

我有一个字符串

(device
    (vfb
        (xxxxxxxx)
        (xxxxxxxx)
        (location 0.0.0.0:5900)
    )
)

(device
    (console
        (xxxxxxxx)
        (xxxxxxxx)
        (location 80)
    )
)

我需要从字符串的“vfb”部分读取位置行。我尝试使用正则表达式,例如

  import re
  re.findall(r'device.*?\vfb.*?\(.*?(.*?).*(.*?\))

但它没有给我所需的输出。

4

3 回答 3

3

最好使用解析器来解决此类问题。幸运的是,在您的情况下,解析器将相当简单:

def parse(source):

    def expr(tokens):
        t = tokens.pop(0)
        if t != '(':
            return {'value': t}
        key, val = tokens.pop(0), {}
        while tokens[0] != ')':
            val.update(expr(tokens))
        tokens.pop(0)
        return {key:val}

    tokens = re.findall(r'\(|\)|[^\s()]+', source)
    lst = []
    while tokens:
        lst.append(expr(tokens))
    return lst

鉴于上面的片段,这将创建一个结构,如:

[{'device': {'vfb': {'location': {'value': '0.0.0.0:5900'}, 'xxxxxxxx': {}}}},
 {'device': {'console': {'location': {'value': '80'}, 'xxxxxxxx': {}}}}]

现在你可以迭代它并获取你需要的任何东西:

for item in parse(source):
    try:
        location = item['device']['vfb']['location']['value']
    except KeyError:
        pass
于 2012-12-26T12:30:47.817 回答
3

通过 Martijn Pieters 的介绍,这是一种 pyparsing 方法:

inputdata = """(device
    (vfb
        (xxxxxxxx)
        (xxxxxxxx)
        (location 0.0.0.0:5900)
    )
)

(device
    (console
        (xxxxxxxx)
        (xxxxxxxx)
        (location 80)
    )
)"""

from pyparsing import OneOrMore, nestedExpr

# a nestedExpr defaults to reading space-separated words within nested parentheses
data = OneOrMore(nestedExpr()).parseString(inputdata)

print (data.asList())

# recursive search to walk parsed data to find desired entry
def findPath(seq, path):
    for s in seq:
        if s[0] == path[0]:
            if len(path) == 1:
                return s[1]
            else:
                ret = findPath(s[1:], path[1:])
                if ret is not None:
                    return ret
    return None
print findPath(data, "device/vfb/location".split('/'))

印刷:

[['device', ['vfb', ['xxxxxxxx'], ['xxxxxxxx'], ['location', '0.0.0.0:5900']]], 
 ['device', ['console', ['xxxxxxxx'], ['xxxxxxxx'], ['location', '80']]]]
0.0.0.0:5900
于 2012-12-26T13:02:12.920 回答
0

也许这会让你开始:

In [84]: data = '(device(vfb(xxxxxxxx)(xxxxxxxx)(location 0.0.0.0:5900)))'

In [85]: m = re.search(r"""
  .....:     vfb
  .....:     .*
  .....:     \(
  .....:         location
  .....:         \s+
  .....:         (
  .....:             [^\)]+
  .....:         )
  .....:     \)""", data, flags=re.X)

In [86]: m.group(1)
Out[86]: '0.0.0.0:5900'
于 2012-12-26T11:21:20.440 回答