-3

How do I write a regex that passes for below conditions in C#

\segment\segment\

a) each segment starts and ends with a backslash

b) segment can be alpha-numeric with dashes, underscore and period allowed (e.g. \some-name\some.other_name\ )

c) the sequence can repeat max 100 times (basically only 100 segments allowed)

Frank Q.
  • 6,001
  • 11
  • 47
  • 62

3 Answers3

2

How about this:

(?<=\\)[A-Za-z\-\.]+(?=\\)

to select any combination of characters you mentioned within the backslashes? Not selecting the backslashes.

Alexander Büse
  • 564
  • 7
  • 15
2

You can try the following:

Regex myRegex = new Regex("^\\(?:[\w\-.]+\\){1,100}$");

The regex starts with matching '\', then matches letters, digits, underscore, hyphens, dots one or more times, ending with a '\'. It finally repeats this one to 100 times.

This version supports unicode path names.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
1

The following is Extended Regular Expressions (ERE). Add any other allowed characters (notably I believe space may be a character you want in, ensuring that the - is left at the end) between the square brackets:

^(\\[\w.-]+){1,100}\\$

(after correcting for a bug in the code, the resulting code is the same as the answer above haha!)

Ezequiel Tolnay
  • 4,302
  • 1
  • 19
  • 28