首页 > 解决方案 > 嵌套方括号

问题描述

我有这样的模式:

word word one/two/three word

我想匹配由/. 我的想法如下:

[\w]+ # match any words
[\w]+/[\w]+ # followed by / and another word
[\w]+[/[\w]+]+ # repeat the latter

但这不起作用,因为我似乎一添加],它就不会关闭内部的摩西,[而是最外部的[

如何使用嵌套方括号?

标签: pythonregex

解决方案


这是使用的一种选择re.findall

import re
input = "word word one/two/three's word apple/banana"
r1 = re.findall(r"[A-Za-z0-9'.,:;]+(?:/[A-Za-z0-9'.,:;]+)+", input)
print(r1)

["one/two/three's", 'apple/banana']

演示


推荐阅读