Parsing valid parent directories with regex

后端 未结 3 1427
感情败类
感情败类 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.

提交回复
热议问题