tigerbyte
tigerbyte

Reputation: 117

C# Regex to match a directory pattern

I would like a regex to run against Directory.GetAllDirectories() e.g.

 Directory.GetDirectories(pathToMonitor, "*.*", SearchOption.AllDirectories)
.Where(path => new Regex(pattern, RegexOptions.IgnoreCase).IsMatch(path))
.ToList();

The directories follow a pattern like this:

[Variable number of directories]\$PROJECT$\$TYPE$\$BRANCH$\[Variable number of directories]

I would like to ignore the first set of [Variable number of directories], followed by exactly 3 directories. I do not want to include directories that have anything after the $BRANCH$ directory. The $TYPE$ directory must be "Ft" or "Dev".

I have the following pattern which almost works...

string pattern = @"\w+\\(Ft|Dev)\\";

Unfortunately that pattern will grab all folders after the $BRANCH$ folder as well.

Concretely, a list of folders like this:

Should be filtered down to this after the regex:

EDIT: Cleaned up formatting on directory pattern

Upvotes: 1

Views: 2183

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

You can do it with this pattern:

@"\w\\(?:Ft|Dev)\\Branch\\?$"

Where $ is an anchor for the end of the string.

Upvotes: 2

Related Questions