MATLAB Answers

sst
0

Legacy implementation of strtrim prior to R2016a

Asked by sst
on 30 Aug 2016
Latest activity Edited by Guillaume
on 31 Aug 2016
It looks like strtrim changed in R2016a to not trim significant whitespace characters. However, I have a need for a legacy implementation. Is it possible to provide one that works in R2016a, but also trims significant whitespace characters?

  0 Comments

Sign in to comment.

1 Answer

Answer by Guillaume
on 30 Aug 2016
 Accepted Answer

regexp(yourstring, '(?<=^\W*)\w.*?(?=\W*$)', 'match', 'once')
should do the trick

  4 Comments

Show 1 older comment
Then, how about?
notspace = ~isspace(yourstring);
trimmed = yourstring(cumsum(notspace) & cumsum(notspace, 'reverse'))
or
notspace = ~isspace(yourstring);
trimmed = yourstring(find(notspace, 1):find(notspace, 1, 'last'))
The first implementation using regexp turned out to be the fastest alternative approach, though still well over ten times slower than the built-in strtrim. I was really hoping TMW would have provided a 'legacy' option for strtrim, like they did for functions like ismember, union, and intersect :)
First of all, I made a mistake in the regex, it should have been \s instead of \W and \S instead of \w (yes upper and lower case should be swapped as well), so:
regexp(yourstring, '(?<=^\s*)\S.*?(?=\s*$)', 'match', 'once')
This will not speed up the regex, the slow down is probably caused by the non-greedy all capturing star .*? followed by the greedy capturing \s*, which causes a lot of backtracking.
However, this regex will do the same and should be significantly faster:
regexp(yourstring, '(?<=^\s*)\S.*\S(?=\s*$)', 'match', 'once')
As for a legacy option for strtrim, this is something you would have to ask Mathworks through a service request.

Sign in to comment.