I'm looking for a simple regex to match any valid windows relative path.
I've been using this:
^\.\.?\\\w+
But it doesn't work on all relative path formats. Does anyone know of a good (and preferably simple) regex that matches valid windows relative paths?
I'm using it in a ValidateScript
block.
I've looked at the Regex101 library, but none exist.
Example paths:
..\meeting_minutes.txt
..\..\profile.txt
Reports\2023\summary.txt
.\Reports\2023\summary.txt
..\Projects\project_a.docx
.\my_file.txt
..\..\data
Regex101 Link: https://regex101.com/r/pomDpL/1
The pattern needs to also match paths with valid special characters like the following:
..\Music#a\file.mp3
..\Music[Genre]\file.mp3
..\Music(Genre)\file.mp3
..\Music-Hardcore-Metal\file.mp3
..\Documents\My+File.xlsx
..\Documents\Some{Document}.py
..\Files\Afilewithweird;Characters'`.doc
..\Music#^@!()-+{};',.`~a\file.mp3
New Regex101 link to tinker with: https://regex101.com/r/cJG2JV/1
This would be my recommendation:
^(?!\w:\\|\\{1,2})((\.{2}\\)+|(\.+\\)?).+
Explanation:
^
matches the beginning of the line
?!
Negative Lookahead
\w:\\
must not match one word char followed by one :
(colon) one \
(backslash)|
OR\\{1,2}
must not match one or two occurrences of \
(backslash)(\.{2}\\)+
matches one or more of two occurrences of .
(dot) followed by one \
(backslash)|
OR(\.?\\)?
matches zero or one of zero or one occurrence of .
(dot) followed by one \
(backslash).+
matches any char one or more timesregex101: https://regex101.com/r/ZMADDT