Python:如何在方括号内获取多个元素

问题描述:

我有一个像这样的字符串/模式:

I have a string/pattern like this:

[xy][abc]

我尝试获取方括号内包含的值:

I try to get the values contained inside the square brackets:

  • xy
  • abc

括号内没有括号.无效:[[abc][def]]

There are never brackets inside brackets. Invalid: [[abc][def]]

到目前为止,我已经知道了:

So far I've got this:

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

但是,这仅给了我第一个方括号的内部值.

But this gives me only the inner value of the first square brackets.

有什么想法吗?我不想使用字符串拆分功能,我敢肯定,仅RegEx就有可能.

Any ideas? I don't want to use string split functions, I'm sure it's possible somehow with RegEx alone.

re.findall是您的朋友在这里:

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