makeValidFieldName.m 1.2 KB

123456789101112131415161718192021222324252627282930
  1. function str = makeValidFieldName(str)
  2. % From MATLAB doc: field names must begin with a letter, which may be
  3. % followed by any combination of letters, digits, and underscores.
  4. % Invalid characters will be converted to underscores, and the prefix
  5. % "x0x[Hex code]_" will be added if the first character is not a letter.
  6. isoct=exist('OCTAVE_VERSION','builtin');
  7. pos=regexp(str,'^[^A-Za-z]','once');
  8. if(~isempty(pos))
  9. if(~isoct)
  10. str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
  11. else
  12. str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
  13. end
  14. end
  15. if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
  16. if(~isoct)
  17. str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
  18. else
  19. pos=regexp(str,'[^0-9A-Za-z_]');
  20. if(isempty(pos)) return; end
  21. str0=str;
  22. pos0=[0 pos(:)' length(str)];
  23. str='';
  24. for i=1:length(pos)
  25. str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
  26. end
  27. if(pos(end)~=length(str))
  28. str=[str str0(pos0(end-1)+1:pos0(end))];
  29. end
  30. end