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

2024-03-28 18:59:36 发布

您现在位置: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

但这只给出了第一个方括号的内部值。

有什么想法吗?我不想使用字符串分割函数,我相信这是有可能的,以某种方式与正则表达式单独。


Tags: 字符串importrevaluedef模式公司括号
3条回答

re.findall你的朋友在这里:

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

我怀疑你在找^{}

this demo

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

如果您想遍历匹配项而不是匹配字符串,可以改为查看^{}。有关详细信息,请参见Python ^{} docs

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

相关问题 更多 >