Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for windows path

Tags:

java

regex

As part of fortify fix we need to validate a filepath. For example,

  1. "C:/Users/<username>/sample1.txt"
  2. "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=.*[\\]\\[!"#$%&'()_*+,/:;<=>?@\\^`{|}~].*
like image 577
Ramya Avatar asked Sep 03 '26 11:09

Ramya


1 Answers

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.
like image 161
dryairship Avatar answered Sep 05 '26 01:09

dryairship



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!