Skip to main content
 首页 » 编程设计

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

2024年10月24日24mfryf

我有一个字符串

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*)? 是一个非捕获组(这样值就不会在结果中输出)可以重复一次或零次(由于最后一个 ?),它匹配一个非单词字符 (\W) 只有当它前面有一个非单词字符或字符串开头 (\B) 后跟 0+ 空格。

Here is the regex demo