正则表达式在python中嵌套括号

我有这样的事情:


Othername California (2000) (T) (S) (ok) {state (#2.1)}

是否有正则表达式代码可获取:


Othername California ok 2.1

也就是说,我想将数字保持在圆括号内,将其依次放在{}内,并将文本“ ok”保持在()内。我特别需要打印出“ ok”字符串(如果包含在我的行中),但是我想去除括号内的其他文本,例如(V),(S)或(2002)。


我知道,正则表达式可能不是解决此类问题的最有效方法。


任何帮助,将不胜感激。


编辑:


该字符串可能会有所不同,因为该行中不包含如果某些信息不可用。文本本身也是可变的(例如,我没有每一行都有“状态”)。因此,可以有例如:


Name1 Name2 Name3 (2000) (ok) {edu (#1.1)}

Name1 Name2 (2002) {edu (#1.1)}

Name1 Name2 Name3 (2000) (V) {variation (#4.12)}


慕标5832272
浏览 269回答 3
3回答

犯罪嫌疑人X

尽管我在评论中说了什么。我找到了一种解决方法:(?(?=\([^()\w]*[\w.]+[^()\w]*\))\([^()\w]*([\w.]+)[^()\w]*\)|.)(?=[^{]*\})|(?<!\()(\b\w+\b)(?!\()|ok解释:(?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # If(?=\([^()\w]*[\w.]+[^()\w]*\))&nbsp; &nbsp; &nbsp; # There is (anything except [()\w] zero or more times, followed by [\w.] one or more times, followed by anything except [()\w] zero or more times)\([^()\w]*([\w.]+)[^()\w]*\)&nbsp; &nbsp; &nbsp; &nbsp; # Then match it, and put [\w.] in a group|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# else.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# advance with one character)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# End if(?=[^{]*\})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# Look ahead if there is anything except { zero or more times followed by }|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# Or(?<!\()(\b\w+\b)(?!\()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Match a word not enclosed between parenthesis|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# Orok&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Match ok
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python