简体   繁体   English

Python正则表达式提取括号

[英]Python regular expression to extract the parenthesis

I have the following unwieldy code to extract out 'ABC' and '(XYZ)' from a string 'ABC(XYZ)' 我有以下繁琐的代码从字符串“ ABC(XYZ)”中提取“ ABC”和“(XYZ)”

import re

test_str = 'ABC(XYZ)'
partone = re.sub(r'\([^)]*\)', '', test_str)
parttwo_temp = re.match('.*\((.+)\)', test_str)
parttwo = '(' + parttwo_temp.group(1) + ')'

I was wondering if someone can think of a better regular expression to split up the string. 我想知道是否有人可以想到更好的正则表达式来拆分字符串。 Thanks. 谢谢。

You may use re.findall 您可以使用re.findall

>>> import re
>>> test_str = 'ABC(XYZ)'
>>> re.findall(r'\([^()]*\)|[^()]+', test_str)
['ABC', '(XYZ)']
>>> [i for i in re.findall(r'(.*)(\([^()]*\))', test_str)[0]]
['ABC', '(XYZ)']
[i for i in re.split(r'(.*?)(\(.*?\))', test_str) if i]

For this kind of input data, we can replace the ( with space+ ( and split by space: 对于这种输入数据,我们可以将(替换为space + (并按空格分隔:

>>> s = 'ABC(XYZ)'
>>> s.replace("(", " (").split()
['ABC', '(XYZ)']

This way we are artificially creating a delimiter before every opening parenthesis. 这样,我们在每个括号前都人为地创建了一个定界符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM