How can I find a simple regex for validating Windows relative paths?

0
15
Asked By CuriousCodeCrafter67 On

I'm trying to find a straightforward regular expression that can match valid Windows relative paths. I've been using `^..?\w+`, but it doesn't seem to capture all cases correctly. I'm implementing this within a `ValidateScript` block and I'd love to hear any suggestions for regex patterns that work well with examples like: `..meeting_minutes.txt`, `....profile.txt`, `Reports2023summary.txt`, `.Reports2023summary.txt`, `..Projectsproject_a.docx`, `.my_file.txt`, and `....data`. I just need a regex to ensure the format is valid without needing it to exist on the filesystem. Here's a link for reference: https://regex101.com/r/pomDpL/1

4 Answers

Answered By FormatFinder On

Do you want to focus on the format of the paths themselves, or are you interested in whether they actually exist?

FormatSeeker -

I'm just trying to see if the path format is valid.

Answered By PathExplorer On

Just keep in mind that a relative path is in relation to your current directory. Like, when PowerShell is opened, it usually starts in `C:windowssystem32`. So, any function to check for relative paths might need to account for the base directory you're relating it to. Also, consider checking out `Resolve-Path` if you haven't already.

Answered By FilePathFanatic On

Have you thought about just using `Test-Path`? It will throw an error if the path doesn’t exist, which could help you out in ensuring it's valid without needing a regex solution. Just do something like this:

```powershell
[Parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_})]
[string] $filePath
```

LogicalLookup -

I need to check the format, not whether the path exists. So a regex is still my best bet.

Answered By DaringDev2023 On

It sounds like you might be getting tangled up in a regex rabbit hole. Just a thought: why do you really need to validate the path? Are you trying to check if the file or folder exists, or maybe just to confirm the structure of the path? Using regex might complicate things more than necessary.

PathPonderer90 -

I'm with you on that idea. You could check if the path contains a colon or starts with `` to find absolute paths, but it's easy to miss cases, which makes your solution unreliable. Why not just use `Test-Path`? That way, you can pass whatever path to the function, whether it's absolute or relative.

RegexRookie -

I just want to ensure that the string format is valid for a relative path. The existence of the file isn't my concern since I have a way to get the full path from the string.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.