簡體   English   中英

Python:如何在方括號內獲取多個元素

[英]Python: How to get multiple elements inside square brackets

我有這樣的字符串/模式:

[xy][abc]

我嘗試獲取方括號內包含的值:

  • y
  • 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']
>>> import re
>>> re.findall("\[(.*?)\]", "[xy][abc]")
['xy', 'abc']

我懷疑您正在尋找re.findall

看到這個演示

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

如果要遍歷匹配而不是匹配字符串,則可以re.finditer 有關更多詳細信息,請參見Python re docs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM