Python:如何在方括号内获取多个元素 [英] Python: How to get multiple elements inside square brackets
本文介绍了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']
这篇关于Python:如何在方括号内获取多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文