簡體   English   中英

深入Python中的方括號

[英]Get inside of square brackets in Python

我有這個字符串。

"ascascascasc[xx]asdasdasdasd[yy]qweqweqwe"

我想將字符串放在方括號內。 像這樣;

"xx", "yy"

我已經嘗試過了,但是沒有用:

a = "ascascascasc[xx]asdasdasdasd[yy]qweqweqwe"
listinside = []
for i in range(a.count("[")):
    listinside.append(a[a.index("["):a.index("]")])
print (listinside)

輸出:

['[xx', '[xx']

您不需要count,可以使用regex, re.findall()可以做到:

>>> s="ascascascasc[xx]asdasdasdasd[yy]qweqweqwe"
>>> import re
>>> re.findall(r'\[(.*?)\]',s)
['xx', 'yy']

\\[匹配字符[從字面上

*? 在零次和無限制次數之間進行匹配,並盡可能少地匹配,並根據需要擴展[懶惰]

\\] ]從字面上匹配字符[]

DEMO

暫無
暫無

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

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