.netregexrelative-path

Looking for a simple regex to match any valid windows relative path, to be used in a Powershell script. (Case insensitive)


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

Edit:

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


Solution

  • This would be my recommendation:

    ^(?!\w:\\|\\{1,2})((\.{2}\\)+|(\.+\\)?).+

    Explanation:

    regex101: https://regex101.com/r/ZMADDT