I have a regex I want to construct for validating the UNC syntax, which is:
\\server\shared\folder\path
I don't care about the server or folder characters, I exclusively want to validate the \thing1\thing2maybe3 syntax, the server and folder names will be validated separately.
This is what I have so far:
(^\\\\\w )(\\{1}\w ) (. (?<!\\)$)
These are my tests:
- MATCH - \\server\multiple\folders\example\path
- FAIL - \\server\\multiple\folders\example\path
- SHOULD FAIL - \\server\multiple\\folders\example\path
- FAIL - \\server\multiplefolders\example\path\
- FAIL - \\server
- FAIL - \\\server\multiple
- SHOULD MATCH - \\server\m
- MATCH - \\server\m\w\z
I'm testing here: https://regex101.com/r/WqF7h7/1
Can anyone help making #3 and #7 fail and match respectively?
#3 has a second double slash after "multiple", this shouldn't be permitted, only at the beginning should there be double slashes. This should fail like #2
#7 has the correct syntax and should be matching like #8
Thanks.
CodePudding user response:
You can use
^\\{1,2}\w (?:\\\w ) $
In Java with the doubled backslashes:
String regex = "^\\\\{1,2}\\w (?:\\\\\\w ) $";
The pattern matches:
^
Start of string\\{1,2}
Match 1 or 2 backslashes\w
Match 1 word characters(?:\\\w )
Repeat 1 times 1 or more word characters$
End of string
Or a bit less strict version matching any char except \
instead of only word characters:
^\\{1,2}[^\\] (?:\\[^\\] ) $