Regex to get the last three folders
Trying to get the last three folders in the path, no matter how many folders are in the path.
As an additional compactification factor, this should only match if the first folder is a specific string.
I have this, but it uses 5 groups and only supports 5 folders.
/(a)/?([^/]+)?/?([^/]+)?/?([^/]+)/?([^/]+)/?([^/]+)/$
Need to get
/a/
$1 = a
$2 =
$3 =
/a/b/
$1 = a
$2 = b
$3 =
/a/b/c/
$1 = a
$2 = b
$3 = c
/a/b/c/d/
$1 = b
$2 = c
$3 = d
/a/b/c/d/e/
$1 = c
$2 = d
$3 = e
/b/c/d/e/
Not a Match because first folder is not "a"
Thanks in advance.
+3
source to share
2 answers
You can use this regex:
/a.*/(\w*?)/(\w*?)/(\w*?)/|/(a)/(?:(\w+?)/)?(\w+?)?
MATCH 1
4. [1-2] `a`
MATCH 2
4. [5-6] `a`
5. [7-8] `b`
MATCH 3
4. [11-12] `a`
5. [13-14] `b`
6. [15-16] `c`
MATCH 4
1. [21-22] `b`
2. [23-24] `c`
3. [25-26] `d`
MATCH 5
1. [33-34] `c`
2. [35-36] `d`
3. [37-38] `e`
I think there must be a better regex for this, but you can go with that.
+2
source to share