进入 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']

你不需要计数,你可以使用正则表达式,re.findall() 可以做到:

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

\[ matches the character [ literally

*? matches Between zero and unlimited times, as few times as possible, expanding as needed [lazy]

\] matches the character ] literally

DEMO