Regex: Find Files and Directories from a Full Path
Regex for each delimiter
Summary | Windows | Unix |
---|---|---|
File name | [^\\]+$ |
[^/]+$ |
Directories | ^.*\\ |
^.*/ |
Since a specific directory | directory.*$ |
directory.*$ |
After a specific directory | (?<=directory\\).*$ |
(?<=directory/).*$ |
Until a specific directory | ^.*directory\\ |
^.*directory/ |
Before a specific directory | .*\\(?=directory) |
.*/(?=directory) |
Examples
Suppose you have this text.
C:\Users\regex\Documents\foo.txt
C:\Users\regex\Documents\bar\baz.txt
C:\Users\regex\Documents\qux\qux\qux.txt
Delete only the file name from the full path
If you use [^\\]+$
to match only the file name and replace it with an empty string, you can extract only the directory path.
C:\Users\regex\Documents\
C:\Users\regex\Documents\bar\
C:\Users\regex\Documents\qux\qux\
Delete only the directory from the full path
If you use ^.*\\
to match only the directory and replace it with an empty string, you can extract only the file name.
foo.txt
baz.txt
qux.txt
Delete only until a specific directory from the full path
If you use ^.*Documents\\
to match only until a specific directory and replace it with an empty string, you can extract only after a specific directory.
foo.txt
bar\baz.txt
qux\qux\qux.txt