Extracting numbers from cell using regex

7 次查看(过去 30 天)
Hi,
I have the following cell:
C = {'2/6';'78/6';'982/47';'11/6'}
I would like to extract all numbers from before / and place them in a new matrix, and all numbers from after / and place them in another matrix.
The result should be something like this:
A=[2;78;982;11] B=[6;6;47;6]
How can i do this? I guess using regex would be the easiest way, but how to write it so it extracts it as explained?
Thank you for your help.

回答(2 个)

Walter Roberson
Walter Roberson 2017-12-10
C = {'2/6';'78/6';'982/47';'11/6'};
One way:
temp = cell2mat(cellfun(@str2double,regexp(C, '(\d+)/(\d+)', 'tokens','once'),'uniform',0));
A = temp(:,1);
B = temp(:,2);
Another way:
temp = cell2mat(regexp(C, '(?<A>\d+)/(?<B>\d+)', 'names'));
A = str2double({temp.A}.');
B = str2double({temp.B}.');
Another way:
temp = cell2mat(cellfun(@str2double,regexp(C,'/','split'),'uniform',0));
A = temp(:,1);
B = temp(:,2);
Another way:
A = str2double(regexp(C,'\d+(?=/)','match','once'));
B = str2double(regexp(C,'(?<=/)\d+','match','once'));

Jos (10584)
Jos (10584) 2017-12-10
You can use cellfun to scan every string:
C = {'2/6';'78/6';'982/47';'11/6'}
V = cellfun(@(c) sscanf(c,'%f/%f'), C, 'un', 0) ;
AB = cat(2,V{:})
A = AB(1,:)
B = AB(2,:)
  5 个评论
kalili
kalili 2017-12-12
Hm, the data was obtained by importing an excel sheet using [~,~,C]=xlsread(filename).
Walter Roberson
Walter Roberson 2017-12-12
What shows up for
class(C{1})
When you use the third output of xlsread(), then anything that looks like a plain number will be converted to numeric but anything else will be left alone. Approximately speaking, it is like
temp = read cells as text
temp_numeric = str2double(temp);
mask = ~isnan(temp_numeric);
temp(mask) = num2cell(temp_numeric(mask))
so '2/6' should have been left alone as text because str2double() if it would be nan. Note that str2num() is not used for this purpose: str2num() would evaluate the text as an expression, getting the 0.333<etc> but that is not going to be used.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by