我试图使用regex查找UNIX样式路径的子路径,我接受三个参数:
root要与之比较的目录。minDepth最低水平下降所需的数量。maxDepth要匹配的级别的最大数量。我创建了以下函数(@items在其他地方定义):
module Navigation
def dig (root = nil, minDepth = 1, maxDepth = nil)
root ||= "/"
@items.select{ |i| !(i.path =~ %r{"\A#{root}(.*?/){#{minDepth},#{maxDepth}}"}).nil? }
end
end我的问题是让正则表达式服从maxDepth,当前正则表达式找到一个匹配,即使在路径中有更多的级别--它只是没有包含在匹配中。例如:
尽管只有/foo/bar/daz/bag/cop/fig/leg匹配,regex %r{\A/foo(.*?/){1,3}}还是匹配路径/foo/bar/daz/。如果在比赛后的任何一点上都有一个正斜杠,我如何修改我的正则表达式以不匹配?
所以:/foo/bar/daz/hey会有匹配的,但/foo/bar/daz/hey/不会。
我试图使用负面的外观,但不是很成功,这很可能是我没有正确地使用他们。
发布于 2014-04-02 14:45:38
这个能行吗?
\A/foo(/[^/]*?){1,3}\Z
module Navigation
def dig (root = nil, minDepth = 1, maxDepth = nil)
root ||= "/"
@items.select{ |i| !(i.path =~ %r{"\A#{root}(/[^/]*?){#{minDepth},#{maxDepth}}\Z"}).nil? }
end
endhttps://stackoverflow.com/questions/22814396
复制相似问题