Reputation: 61
As part of fortify fix we need to validate a filepath. For example,
"C:/Users/<username>/sample1.txt"
"C:\Users\<username>\sample1.txt"
We have tried with the below regex for validating the above paths but we ended up with error when a filepath contains \
.
So please suggest the valid regex which can accept both the slashes in a filepath.
Validator.FilePath=.*[\\]\\[!"#$%&'()_*+,/:;<=>?@\\^`{|}~].*
Upvotes: 6
Views: 19915
Reputation: 954
Here is my solution:
^(?i)\s*([a-z]:/?)?(?:[^?*:;|<>\r\n\\]*)(/\1*|\1*)(.\1*)*[^.]$
satisfies:
c:
c:/
c:notepad++
c:/notepad++
notepad
C:/not epad++/notepad++/notepad++.exe.txt.xaml
C:notepad++/notepad++/notepad++.exe.txt.xaml
C:notepad++//notepad++/notepad++...exe.txt.xaml
C:notepad++/notepad++
.xaml
c:notepad++/
C:/notepad++/notepad++/
C:/notepad++/notepad++/a
C:/notep ad++/notepad++
But not:
C:notepad++/notepad++/notepad++.exe.txt.
Upvotes: 1
Reputation: 649
FWIW, this is the pattern I've used for ages to validate any valid Windows path + file:
^
(?<drive>[a-z]:)?
(?<path>(?:[\\]?(?:[\w !#()-]+|[.]{1,2})+)*[\\])?
(?<filename>(?:[.]?[\w !#()-]+)+)?[.]?
$
It accommodates the drive letter being present or absent, an optional root marker, relative paths ("." and ".."), and periods in file and folder names. It also makes extracting that information simple/easy via capture-group labels. The lone caveat is that it necessitates a secondary check for double-periods in the path names which it passes..
Upvotes: 6
Reputation: 64
Validator.FilePath=(?:[a-zA-Z]\\:|[\\\\\\\\|/]+[\\w\\.]+)[\\\\|/]?([\\w]+[\\\\|/])*[\\w]*(\\.\\w+)$
Upvotes: -1
Reputation: 6077
You can try:
[a-zA-Z]:[\\\/](?:[a-zA-Z0-9]+[\\\/])*([a-zA-Z0-9]+\.txt)
[a-zA-Z]:
is for the drive letter and :
.[\\\/]
to match either \
or /
.(?:[a-zA-Z0-9]+[\\\/])*
is for folder names. You can add any charcters in the character class that you may need. I used only a-zA-Z0-9
.([a-zA-Z0-9]+\.txt)
is for the file name and .txt
extension - it matches the file name, with the extension, and captures it.Upvotes: 7