【问题标题】:Python: How to get multiple elements inside square bracketsPython:如何在方括号内获取多个元素
【发布时间】:2012-03-13 06:45:10
【问题描述】:

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

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

【问题讨论】:

  • 你检查过m.group(2)

标签: python regex pattern-matching match python-2.7


【解决方案1】:

我怀疑您正在寻找re.findall

this demo:

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

如果你想迭代匹配而不是匹配字符串,你可以查看re.finditer。详情请见Python re docs

【讨论】:

  • 你不应该逃避内心]?
【解决方案2】:
>>> import re
>>> re.findall("\[(.*?)\]", "[xy][abc]")
['xy', 'abc']

【讨论】:

    【解决方案3】:

    re.findall 是你的朋友:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-28
      • 2022-01-16
      • 2021-10-16
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 2011-01-07
      相关资源
      最近更新 更多