Trying to figure out a regex for validating a network path ie: \\comp\xyz
or \\comp
or \\comp\x\y\z\storage
or something much more lengthy on all parts but the jist of it is hopefully conveyed.
What I have currently is a simple input field, that I have a user passing information through. Thing of it is I don't want them to put it in wrong as the backend connects to a client that uses it to run processes on computers across a network, so last thing I need is someone mistyping something and being the cause of something else breaking. So I figure a quick preg_match will do me just fine in confirming this from the PHP side I am currently work with but I do have a need to work this into JavaScript and a layer thats built on Ruby so I not knowing if all regex is equal or not I need one that works on all levels..
Also to save me time later in coming back I will eventually need to figure out a regex that will allow a user to do either local path ie: C:\
, X:
, H:\path\to\folder
or a network path as mentioned prior.
\\comp\x\y\z\storage
:
/^\\(\\[^\s\\]+)+(\\)?$/
H:\path\to\folder
:
/^([A-Za-z]:(\\)?|[A-Za-z]:(\\[^\s\\]+)+)(\\)?$/
Both
:
/^(\\(\\[^\s\\]+)+|([A-Za-z]:(\\)?|[A-z]:(\\[^\s\\]+)+))(\\)?$/
Working demo: http://jsfiddle.net/DerekL/gLfdv/
this seems to work for me:
([A-Z]:|\\)(\\[a-z0-9]+)*
let me know if you've got any problems (undesirable or additional desired) matches
and to validate a WHOLE field, use:
^([A-Z]:|\\)(\\[a-z0-9]+)*$
EDIT a small revision was necessary to match ALL of your suggestions (my bad):
^([A-Z]:|\\)(\\$|\\[a-z0-9]+)*$
General case:
/^(\\\\\w+)(\\\w+)$/g // matches \\comp, \\comp\xyz, \\comp\x\y\z\storage
Specific case:
/^([A-Z]:)(\\|\\\w+)*$/g // matches C:\, X:, H:\path\to\folder
For the first one I have:
^\\(\\[a-zA-Z_]\w*)+$
and the second one:
^[a-zA-Z]:(\\([a-zA-Z_]\w*)*)*$
This will match UNC paths that start with an ip address and can handle spaces in the file / folder names. Also validates standard path formats e.g. C:\Users\User\some person\file.txt
/^((\\\\[a-zA-Z0-9-\.]+\\[a-zA-Z0-9`~!@#$%^&(){}'._-]+([ ]+[a-zA-Z0-9`~!@#$%^&(){}'._-]+)*)|([a-zA-Z]:))(\\[^ \\/:*?""<>|]+([ ]+[^ \\/:*?""<>|]+)*)*\\?$/
I modified the answers from: PHP Regex for matching a UNC path
and: http://regexlib.com/REDetails.aspx?regexp_id=2285&AspxAutoDetectCookieSupport=1
See it in action at https://jsfiddle.net/megamania/q5ncy7t6/