2012-02-22 88 views
7

我有一個字符串/模式是這樣的:的Python:如何獲得方括號內的多個元素

[xy][abc] 

我試圖讓包含在方括號內的值:

  • XY
  • abc

括號內沒有括號。無效:[[abc][def]]

到目前爲止,我有這樣的:

import re 
pattern = "[xy][abc]" 
x = re.compile("\[(.*?)\]") 
m = outer.search(pattern) 
inner_value = m.group(1) 
print inner_value 

但是這給了我只有第一方括號內的值。

任何想法?我不想使用字符串拆分函數,我確信它可以以某種方式與RegEx單獨使用。

+0

你有沒有檢查過'm.group(2)' – Endophage 2012-02-22 21:26:28

+0

組(2)是無 – Patric 2012-02-22 21:45:53

回答

17

re.findall是你的朋友在這裏:

>>> import re 
>>> sample = "[xy][abc]" 
>>> re.findall(r'\[([^]]*)\]',sample) 
['xy', 'abc'] 
4
>>> import re 
>>> re.findall("\[(.*?)\]", "[xy][abc]") 
['xy', 'abc'] 
3

我懷疑你正在尋找re.findall

this demo

import re 
my_regex = re.compile(r'\[([^][]+)\]') 
print(my_regex.findall('[xy][abc]')) 
['xy', 'abc'] 

如果要遍歷匹配,而不是匹配的字符串,你可能看re.finditer來代替。有關更多詳細信息,請參閱Python re docs

+0

你不應該逃跑嗎? – Gangnus 2017-08-29 11:13:59