可以用递归匹配[k=v]的正则表达式?

2024-09-28 23:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为下面的例子写一个Python2正则表达式我还没有做可行性分析

  • 示例输入字符串:the quick [brown_1=fox] jumps over the [lazy=dog]
  • 正则表达式匹配项列表:["[brown_1=fox]", "[lazy=dog]"]

基本上,我希望匹配所有[\w+=.*]子字符串,并将它们输出到一个列表中。看起来我想在这里使用的API是re.findall,但是在Python2中什么是合适的正则表达式呢

在这种特定情况下,子字符串[brown_1=fox][lazy=dog]分别与regex:[\w+=.*]匹配

注意: 允许以下输入字符串:the quick [brown=[fox[a=b][c=d]]] jumps over。i、 e.在匹配[\w+=.*]的单个元素中,[]=字符可能再次出现。但可以保证,在第一个“等于”字符之前,只有字母数字字符和下划线


Tags: the字符串示例列表quick字符lazy例子
2条回答

我想你需要一个简单的状态机

def parse(s):
    stack = []
    parts = []
    current = []
    for c in s:
      if c == "[":
        current.append("")
        stack.append(c)
      elif c == "]" and stack:
        stack.pop()
        parts.insert(0,current.pop())
      elif stack:
        current[-1] += c
    return parts

print(parse("the quick [brown=[fox[a=b][c=d]]] jumps over"))
# ['brown=', 'fox', 'c=d', 'a=b']

您可以安装替代的^{} module,它支持递归模式^{},这样您就可以像这样使用findall()方法:

import regex
s = 'the quick [brown=[fox[a=b][c=d]]] jumps over the [lazy=dog]'
print(regex.findall(r'\[(?>[^[\]]|(?R))*\]', s))

这将输出:

['[brown=[fox[a=b][c=d]]]', '[lazy=dog]']

相关问题 更多 >