regexpathshared-directory

Strict regular expression for shared/network folder


I'm trying to limit user's input to a valid shared folder path like

\\\computer-name\drive\optional_folder1\optional_folder2\

  1. Starts with 2 slashes followed by computer name, single slash, and drive letter. (I got this part down)
  2. Ends with 0 or 1 slash.
  3. Can have zero or more single slash followed by folder name (\folder).
  4. No multiple slashes besides the first one.

I've tried to look around and around and make my own regex, but I can't find the perfect answer. This is my current regex:

^((\\{2})([A-Za-z -._]+)(\\{1})([A-Za-z -._]+))(\\{1}([A-Za-z .-_])+)*(\\?)$

Any hints will be appreciated.

Thanks, guys.


Solution

  • I've simplified it a bit:

    ^(\\)(\\[\w\.-_]+){2,}(\\?)$
    

    So basically you want to have

    ^(\\)              # start with slash
    (\\[\w\.-_]+)      # followed by group of slash and name
    {2,}               # which should be two or more times
    (\\?)$             # last slash(es)
    

    Demo: https://regex101.com/r/mD2yL7/110