我有一个字符串
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)']
但是如果括号组位于开头,这感觉有点笨拙并且会失败。我可以对此进行检查,但就像我说的,感觉有点笨拙。有接受者吗?
最佳答案
您可以在模式的开头使用(?:\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*)?
是一个非捕获组(因此该值不会在结果中输出),可以重复一次或零次(由于最后一个 ?
),并且仅当它前面有非单词字符或字符串开头 (\B
) 并后跟 0+ 空格。
关于python - 使用正则表达式解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35861970/