如何提取括号内的所有内容

时间:2014-12-24 12:49:56

标签: python regex

如何提取括号内的所有内容?

string = "int funt (char* dst, char* src, int length); void bar (int a, short b, unsigned long c) ";

import re
pat = re.compile(r'([^(]+)\s*\(([^)]+)\)\s*(?:,\s*|$)')

lst = [t for t in pat.findall(string)]
print lst

没有给出正确的结果。

2 个答案:

答案 0 :(得分:1)

(?<=\()[^)]+(?=\))

试试这个。看看演示。

https://regex101.com/r/gQ3kS4/35

import re
p = re.compile(ur'(?<=\()[^)]+(?=\))')
test_str = "int funt (char* dst, char* src, int length); void bar (int a, short b, unsigned long c) "

re.findall(p, test_str)

enter image description here

答案 1 :(得分:1)

您可以使用re.findall查找括号内的内容:

>>> string = "int funt (char* dst, char* src, int length); void bar (int a, short b, unsigned long c) "
>>> l= re.findall(r'\((.*?)\)',string)
['char* dst, char* src, int length', 'int a, short b, unsigned long c']

然后如果你想要split他们的话:

>>> [i.split() for i in l]
[['char*', 'dst,', 'char*', 'src,', 'int', 'length'], ['int', 'a,', 'short', 'b,', 'unsigned', 'long', 'c']]