嵌套方括号

时间:2018-06-11 15:21:26

标签: python regex

我有这样的模式:

word word one/two/three word

我希望匹配/分隔的群组。我的想法如下:

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

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

如何使用嵌套的方括号?

2 个答案:

答案 0 :(得分:0)

以下是使用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']

Demo

答案 1 :(得分:0)

我建议您使用一个非常接近您的简单正则表达式和@Tim Biegeleisen的答案,但不完全相同:

import re
words = "word word one/two/three's word other/test"
result = re.findall('[\w\']+/[\w\'/]+', words)
print(result)  # ["one/two/three's", 'other/test']