Parsing valid parent directories with regex

后端 未结 3 1426
感情败类
感情败类 2021-01-29 09:58

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.

相关标签:
3条回答
  • 2021-01-29 10:19

    One solution building on idea in this other question:

    • reverse the string to be matched: d/c/b/a For instance in PHP use strrev($string )
    • match with (?=(/(?:\w+(?:/|$))+))

    This give you

    /c/b/a
    /b/a
    /a
    

    Then reverse the matches with strrev($string )

    This give you

    a/b/c/
    a/b/
    a/
    

    If you had .NET not PCRE you could do matching right to left and proably come up with same.

    0 讨论(0)
  • 2021-01-29 10:23

    Completely different answer without reversing string.

    (?<=((?:\w+(?:/|$))+(?=\w)))
    

    This matches

    a/
    a/b/
    a/b/c/
    

    but you have to use C# which use variable lookbehind

    0 讨论(0)
  • 2021-01-29 10:28

    Yes, it's possible:

    /([^\/]*)\//
    

    So basically it replaces your .*? with [^/]*, and it does not have to be non-greedy. Since / is a special character in your case, you will have to escape it, like so: [^\/]*.

    0 讨论(0)
提交回复
热议问题