I have a regex I want to construct for validating the UNC syntax, which is:
\serversharedfolderpath
I don’t care about the server or folder characters, I exclusively want to validate the thing1thing2maybe3 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 – \servermultiplefoldersexamplepath
- FAIL – \server\multiplefoldersexamplepath
- SHOULD FAIL – \servermultiple\foldersexamplepath
- FAIL – \servermultiplefoldersexamplepath
- FAIL – \server
- FAIL – \servermultiple
- SHOULD MATCH – \serverm
- MATCH – \servermwz
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.
Advertisement
Answer
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 backslashesw+
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}[^\]+(?:\[^\]+)+$