Reputation: 12425
I want to check if a string represents a full path of a file, like this:
p = 'C:\my\custom\path.txt'
The file does not exist, so commands like isdir
and exist
return false to me, but still the format of the string represents a valid path for my operating system, while the following one does not because it has an invalid character for the file name:
p = 'C:\my\custom\:path.txt'
So I'd like to know how to check if a string represents a valid file path without needing that the file actually exists.
Upvotes: 4
Views: 1728
Reputation: 73
function bool = isLegalPath(str)
bool = true;
try
java.io.File(str).toPath;
catch
bool = false;
end
end
Upvotes: 1
Reputation: 10440
You can also let Matlab try for you:
if ~isdir(p)
[status, msg] = mkdir(p);
if status
isdir(p)
rmdir(p)
else
error(msg)
end
end
First, you check if the folder exists, if not you try to create it. If you succeed then you delete it, and if not you throw an error.
This is not recommended for checking many strings but has the advantage of being cross-platform.
Upvotes: 2
Reputation: 8781
You might want to use the regexp
function with a regular expression to match Windows paths.
if isempty(regexp(p, '^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$', 'once'))
// This is not a path
end
Upvotes: 5