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

时间:2022-07-20 21:43:37

I have a string/pattern like this:

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

[xy][abc]

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

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

  • xy
  • XY
  • abc
  • ABC

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

括号内没有括号。无效:[[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.

但这只给了我第一个方括号的内在价值。

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

有任何想法吗?我不想使用字符串拆分函数,我确信单独使用RegEx可能会以某种方式。

3 个解决方案

#1


17  

re.findall is your friend here:

re.findall是你的朋友:

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

#2


4  

>>> import re
>>> re.findall("\[(.*?)\]", "[xy][abc]")
['xy', 'abc']

#3


3  

I suspect you're looking for re.findall.

我怀疑你正在寻找re.findall。

See this demo:

看这个演示:

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

If you want to iterate over matches instead of match strings, you might look at re.finditer instead. For more details, see the Python re docs.

如果你想迭代匹配而不是匹配字符串,你可能会改为查看re.finditer。有关更多详细信息,请参阅Python re docs。

#1


17  

re.findall is your friend here:

re.findall是你的朋友:

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

#2


4  

>>> import re
>>> re.findall("\[(.*?)\]", "[xy][abc]")
['xy', 'abc']

#3


3  

I suspect you're looking for re.findall.

我怀疑你正在寻找re.findall。

See this demo:

看这个演示:

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

If you want to iterate over matches instead of match strings, you might look at re.finditer instead. For more details, see the Python re docs.

如果你想迭代匹配而不是匹配字符串,你可能会改为查看re.finditer。有关更多详细信息,请参阅Python re docs。