【发布时间】:2013-06-11 18:53:42
【问题描述】:
我有一个包含路径的变量,我想从路径中提取第 6 个文件夹,但第 7 个文件夹可能会出现也可能不会出现。在这两种情况下......正则表达式应该返回“三”,但第一个示例无法匹配。我试过用?表示可选,但我的尝试不正确。
我需要在正则表达式中进行哪些更改以使其在两种情况下都匹配:
path = "//network/path/folder/_one/two/three" # fails
path = "//network/path/folder/_one/two/three/four" # works
p = re.compile('^//network/path/folder/_.*?/.*?/(.*?)/') # compile the regex
m = re.search(p, path) # regex search
if m: # regex matched
print "6th folder =",m.group(1)
【问题讨论】:
-
path.split('/')[7]有什么问题 ->'three'?
标签: python regex non-greedy