how to create a function that error checks if the input is a valid text file name in matlab

Here is a MATLAB function that checks if an input is a valid file name (including the extension ".txt"). The function returns a boolean value valid that is true if the input meets the criteria, and false if it does not.

main.m
function valid = isValidTextFileName(filename)

% Define the regular expression that filenames must match
% This expression specifies that the filename must:
%   - Start with a letter or number
%   - Optionally contain additional letters, numbers, underscores, or hyphens
%   - End with the extension ".txt"
regex = '^[a-zA-Z0-9][a-zA-Z0-9_-]*\.txt$';

% Use the MATLAB function "regexp" to match the filename against the regular expression
matches = regexp(filename, regex);

% If "matches" is empty, it means the filename did not match the regular expression
% If "matches" is not empty, it means the filename did match the regular expression
if isempty(matches)
    valid = false;
else
    valid = true;
end

end
716 chars
22 lines

To use this function, simply call it with a string that represents the filename you want to check. For example:

main.m
filename1 = 'valid_file_name.txt';
filename2 = 'invalid_file*name.txt';

isValid1 = isValidTextFileName(filename1) % Returns true
isValid2 = isValidTextFileName(filename2) % Returns false
188 chars
6 lines

gistlibby LogSnag