MATLAB Answers

a1
0

regexprep() skip first occurrence

Asked by a1
on 13 Mar 2019
Latest activity Commented on by a1
on 13 Mar 2019
Is there a way to use regexprep() but skip the first occurrence of a space?
mystring = 'this is my string';
desired return:
mystring2 = 'this ismystring';

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by Akira Agata
on 13 Mar 2019
 Accepted Answer

How about using regexp to find the position of spaces, and delete 2nd~Nth spaces? Like:
mystring = 'this is my string';
pos = regexp(mystring,'\s');
mystring(pos(2:end)) = [];

  1 Comment

a1
on 13 Mar 2019
So simple and clean, thanks so much!

Sign in to comment.


Answer by a1
on 13 Mar 2019
Edited by a1
on 13 Mar 2019

this works but perhaps is not most efficient:
[spaces,letters] = regexp(mystring, ' ', 'match', 'split', 'forceCellOutput');
spaces = [spaces{:}];
letters = [letters{:}];
mystring2 = [sprintf('%s',letters{2:end-1}), letters{end}];
mystring2 = strcat(char(letters(1)), {' '}, mystring2)

  0 Comments

Sign in to comment.