Splitting a string of numbers and '|'

[EDIT: Tue Jun 21 20:43:11 UTC 2011 - Reformat - MKF]
I cant find anything on the help for regexp that gives a way to split up numbers.
I have '1 | 2' and I need to get '1' and '2' as two separate strings.
I am getting this string from a listbox
Pos = get(handles.PositionList,'String')
Reg_num = get(handles.PositionList,'Value')
Reg_num is so that MATLAB knows which line is selected.

 Réponse acceptée

Matt Fig
Matt Fig le 21 Juin 2011

2 votes

str = '1 | 2';
S = regexp(str,'\d+','match')
Now S is a 1-by-2 cell array.
strcmp(S{1},'1')
strcmp(S{2},'2')

4 commentaires

Brittany
Brittany le 21 Juin 2011
yay! thank you
Brian
Brian le 24 Juin 2011
Is there a way to do this for mixed data strings?
str = '1 | 2|asdf| 123';
S = regexp(str,????)
strcmp(S{1},'1')
strcmp(S{2},'2')
strcmp(S{3},'asdf')
strcmp(S{4},' 123')
Brian
Brian le 24 Juin 2011
Jan Simon's method below works for mixed data strings.
Walter Roberson
Walter Roberson le 24 Juin 2011
See Jan's solution for that.

Connectez-vous pour commenter.

Plus de réponses (2)

Jan
Jan le 22 Juin 2011

1 vote

Another solution:
strtrim(regexp('1 | 2', '\|', 'split'))
Walter Roberson
Walter Roberson le 21 Juin 2011

0 votes

Pos = textscan(get(handles.PositionList,'String'), '%d', 'Delimiter', '|');
Pos{1}(get(handles.PostionList,'Value'))
Caution: If I recall correctly, I have seen cases where when you construct a listbox using '|' separated options, that the uicontrol internally converted this into a cell array of strings. It would therefore be more robust to check whether the 'String' returned was indeed ischar() or if it was iscell() instead.

Catégories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by