MATLAB: Search string for special characters

charactersregexpspecial

Hi all,
I have a program that saves and loads data to and from a .mat file. Currently the UIPUTFILE and save function method I am using allows the user to save files with special characters. They then cannot load this file again. The most common issue is users saving the file with a period.
How can I search the string for special characters? I want to throw up an error message if the user tries to save the file with a filename that MATLAB will not be able to load with UIGETFILE and the load function.
I have tried regexp but I am struggling to make it do what I want, even using backslashes in front of the characters in places.
if ~isempty(regexp(filename, '[/\*:?"<>|!]'))
uiwait(msgbox('Filename contains illegal characters.' 'Filename Error','error','modal'));
else
save(SavePath,'DataStructure');
end
Thanks,
Matt

Best Answer

It is invariably easier to build a short list of the permitted characters than an long (and most likely incomplete) list of forbidden characters (trust me, there are more characters out there than you would believe).
Adapt this to your list of "permitted characters":
>> rgx = '^[\w-]+\.[\w]+$';
>> regexp('okayname.txt',rgx)
ans = 1
>> regexp('bad()nam!e.txt',rgx)
ans = []
I know that it can be a challenge to create a working regular expression, and so to help with this I wrote a tool iregexp that you can download from MATLAB FEX:
It lets you try different parse and match string combinations, and shows regexp's outputs in real time as you type.