2014-12-24 77 views
0

如何提取括號內的所有內容?如何提取括號內的所有內容

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 

沒有給出正確的結果。

回答

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

+0

如何在python中編寫該代碼? –

+1

@UrsaMajor我給了代碼。 – vks

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']] 
+0

name'l'is not defined –

+1

@UrsaMajor oh ...我想念它,你需要將're.findall'的結果分配給l,我編輯答案 – Kasramvd

+0

非常好。謝謝。 –