Search string for special characters
古いコメントを表示
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
3 件のコメント
Stephen23
2017 年 9 月 8 日
"The most common issue is users saving the file with a period"
The period is permitted in Windows filenames. What OS are you using?
Matt
2017 年 9 月 8 日
Milos Matovic
2020 年 11 月 11 日
Matt, your code works for me and it covers all invalid chars for file names as specified by Windows.
Only change i made is added a double backslash because it is a escape character so regular expression was not accounting for it.
if ~isempty(regexp(filename, '[/\\*:?"<>|!]'))
採用された回答
その他の回答 (2 件)
Pal Szabo
2017 年 9 月 8 日
0 投票
Can't you use strrep? You can replace the special characters with something which works. https://uk.mathworks.com/help/matlab/ref/strrep.html
Matt
2017 年 9 月 8 日
1 件のコメント
Some notes:
- Do not do this, it is an unreliable and obfuscated way to remove a file extension:
file_without_extension = file(1:(length(file)-4))
Instead simply use fileparts: it is simpler and correct for any length extension.
- \s matches all whitespace characters. Do you really want vertical tab in your filenames?
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!