Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何在方括号内获取多个元素_Python_Regex_Pattern Matching_Match_Python 2.7 - Fatal编程技术网

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

Python:如何在方括号内获取多个元素,python,regex,pattern-matching,match,python-2.7,Python,Regex,Pattern Matching,Match,Python 2.7,我有这样一个字符串/模式: [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 但这只给出了第一个方括号的内部值 有什么想法吗?我不想使用字符串拆

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

[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是可能的。

re.findall
是您的朋友:

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

我怀疑你在找我

见:


如果您想迭代匹配而不是匹配字符串,您可以查看。有关更多详细信息,请参阅。

您是否已选中
m.group(2)
您是否应该退出内部]?
>>> import re
>>> re.findall("\[(.*?)\]", "[xy][abc]")
['xy', 'abc']
import re
my_regex = re.compile(r'\[([^][]+)\]')
print(my_regex.findall('[xy][abc]'))
['xy', 'abc']