Search code examples
regexregular-language

Regex for validating path


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)


Solution

  • 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.