使用正则表达式解析字符串

时间:2016-03-08 08:00:40

标签: python regex

我有一个字符串

txt = 'text1 & ("text2" | "text3" | "text4") & "text5" ! (text6 | text7 | text8)'

让我说我想解析它,所以我最终得到括号之间的元素。我的模式看起来像

pattern = '\(([^\)(]+)\)'

使用python我最终得到两组

>>> print re.findall(pattren, text)
['"text2" | "text3" | "text4"', 'text6 | text7 | text8']

让我们说想要找到像

这样的东西
>>> print re.findall(magic_pattren, text )
['& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']

magic_pattren将会是什么的任何猜测。我可以使用字符串操作以我的方式工作到所需的输出。

 >>> print [txt[str.find(txt, a)-3: 1+len(a)+str.find(txt, a)] for a in re.findall(pattren, txt)]
 ['& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']

但是如果括号组在开头,这感觉有点笨拙并且失败。我可以添加一个检查,但就像我说的感觉有点笨重。任何人?

1 个答案:

答案 0 :(得分:2)

您可以在模式的开头使用(?:\B\W\s*)?可选组:

import re
p = re.compile(r'(?:\B\W\s*)?\([^()]+\)')
test_str = "(text9 & text10) & text1 & (\"text2\" | \"text3\" | \"text4\") & \"text5\" ! (text6 | text7 | text8)"
print(p.findall(test_str))

sample demo的结果:['(text9 & text10)', '& ("text2" | "text3" | "text4")', '! (text6 | text7 | text8)']

(?:\B\W\s*)?是非捕获组(因此结果中不输出该值),可以重复一次或零次(由于最后?),并且匹配非单词字符(\W),前提是前面带有非单词字符或字符串开头(\B),后跟0 +空格。

Here is the regex demo