Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: check if string has a correct file path syntax

Tags:

path

matlab

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.

like image 364
Jepessen Avatar asked Jan 29 '23 21:01

Jepessen


2 Answers

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
like image 73
Horia Coman Avatar answered Feb 02 '23 21:02

Horia Coman


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.

like image 27
EBH Avatar answered Feb 02 '23 22:02

EBH