问题描述
给定表示完全限定子目录的字符串 a/b/c/d
我想为父树的每一步生成一系列字符串,即 a/b/c
、a/b
和 a
.
Given the string a/b/c/d
which represents a fully-qualified sub-directory I would like to generate a series of strings for each step up the parent tree, i.e. a/b/c
, a/b
and a
.
使用正则表达式我可以做一个非贪婪的 /(.*?)\//
这会给我 a
, b
的匹配> 和 c
或一个贪婪的 /(.*)\//
这会给我一个 a/b/c
的匹配.有没有办法可以在单个正则表达式中获得上面指定的所需结果,或者它本质上无法创建两个吃相同字符的匹配项(如果有意义的话)?
With regex I can do a non-greedy /(.*?)\//
which will give me matches of a
, b
and c
or a greedy /(.*)\//
which will give me a single match of a/b/c
. Is there a way I can get the desired results specified above in a single regex or will it inherently be unable to create two matches which eat the same characters (if that makes sense)?
请让我知道这个问题是否在其他地方得到了回答......我已经看过了,但什么也没找到.
Please let me know if this question is answered elsewhere... I've looked, but found nothing.
注意这个问题是关于正则表达式是否可行.我知道除了正则表达式还有很多方法.
Note this question is about whether it's possible with regex. I know there are many ways outside of regex.
推荐答案
一个基于 另一个问题:
- 反转要匹配的字符串:
d/c/b/a
例如在 PHP 中使用strrev($string )
- 匹配
(?=(/(?:\w+(?:/|$))+))
- reverse the string to be matched:
d/c/b/a
For instance in PHP usestrrev($string )
- match with
(?=(/(?:\w+(?:/|$))+))
这给你
/c/b/a
/b/a
/a
然后用 strrev($string )
这给你
a/b/c/
a/b/
a/
如果您使用的是 .NET 而不是 PCRE,您可以从右到左进行匹配,并且可能会得出相同的结果.
If you had .NET not PCRE you could do matching right to left and proably come up with same.
这篇关于使用正则表达式解析有效的父目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!