MrA MrA - 4 years ago 290
Java Question

Java regular expression for file path

I am developing an application a where user need to supply local file location or remote file location. I have to do some validation on this file location.

Below is the requirement to validate the file location.

Path doesn't contain special characters


And path like "c:" is also not valid.

Paths like

  • c:\

  • c:\newfolder

  • \\casdfhn\share

are valid while

  • c:

  • non

  • \\casfdhn

are not.

I have implemented the code based on this requirement:

String FILE_LOCATION_PATTERN = "^(?:[\\w]\\:(\\[a-z_\\-\\s0-9\\.]+)*)";
String REMOTE_LOCATION_PATTERN = "\\\\[a-z_\\-\\s0-9\\.]+(\\[a-z_\\-\\s0-9\\.]+)+";

Pattern locationPattern = Pattern.compile(FILE_LOCATION_PATTERN);
Matcher locationMatcher = locationPattern.matcher(iAddress);
if (locationMatcher.matches()) {
return true;

locationPattern = Pattern.compile(REMOTE_LOCATION_PATTERN);
locationMatcher = locationPattern.matcher(iAddress);

return locationMatcher.matches();


worklocation' pass
'C:\dsrasr' didnt pass (but should pass)
'C:\saefase\are' didnt pass (but should pass)
'\\asfd\sadfasf' didnt pass (but should pass)
'\\asfdas' didnt pass (but should not pass)
'\\' didnt pass (but should not pass)
'C:' passed infact should not pass

I tried many regular expression but didn't satisfy the requirement. I am looking for help for this requirement.

Answer Source

The following should work:


The lines highlighted in green and red are those that passed. The non-highlighted lines failed.

Bear in mind the regex above is not escaped for java

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download