Issue with your RegEx
Your supplied RegEx is working on the test-cases.
You could even reduce it by removing backslashes \\
and outer pair of parentheses. Begin ^
and end $
are only needed once (around the two alternatives).
Possible Solution using Regular Expression
You can test the RegEx on RegexPlanet.com (click on Java-Button for tests)
^/|(/[a-zA-Z0-9_-]+)+$
or equivalent (see demo on RegexPlanet)
^/|(/[\w-]+)+$
Explained:
\w
matches a word-character (same as [a-zA-Z0-9_]
, not matching the dash).
Implementation in Java code:
public boolean isValidLinuxDirectory(String path) {
Pattern linuxDirectoryPattern = Pattern.compile("^/|(/[a-zA-Z0-9_-]+)+$");
return path != null && !path.trim().isEmpty() && linuxDirectoryPattern.matcher( path ).matches();
}
Alternative Solution using File
Note the docs on isDirectory():
Returns:
true
if and only if the file denoted by this abstract pathname exists and is a directory; false
otherwise
So it may only validate your requirements (valid Linux folder) if run on a Linux machine and if the folder/directory exists.
public boolean isValidExistingDirectory(String path) {
if (path == null || path.trim().isEmpty()) return false;
File file = new File( path );
return file.isDirectory();
}
Extended Solution
As stated in comment the special form of root //
should also be valid. Then use this RegEx:
^/|//|(/[\w-]+)+$
It supports:
- root-directory
/
- special form of root-directory
//
- any non-root directory, which name is composed out of alphas, numbers, dash or underscore (e.g.
/abc/123/_abc-123
)
See also