Laurengineer
Laurengineer

Reputation: 747

Splitting strings using sscanf using matlab

I've been trying to reformat an array I have with file names in the format SIM1_T-1-0.000010.cas.gz into the individual parts: SIM1_T-1-, 0.000010 and .cas.gz but I haven't been having much success, any suggestions?

The couple of lines I've been trying:

for i = 1:length(casFiles)
    casNames(i,:) = sscanf(casFiles{i,1}, '%s');
end

Upvotes: 2

Views: 246

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112699

I'm assuming you have a single string (you don't specify which type of array you have; anyway you can always loop over all strings), and that the spliting pattern is to define the second part as "some digits - decimal point - dome digits".

str = 'SIM1_T-1-0.000010.cas.gz'; %// string to be split    
pattern = '\d+\.\d+'; %// pattern for central (second) part

part13 = regexp(str, pattern, 'split');
part2 = regexp(str, '\d+\.\d+', 'match');

part1 = part13{1};
part2 = part2{1} ;
part3 = part13{2};

Result:

>> part1
part1 =
SIM1_T-1-

>> part2
part2 = 
0.000010

>> part3
part3 =
.cas.gz

Upvotes: 3

damienfrancois
damienfrancois

Reputation: 59180

You can handle this with a regexp:

>> tokens = regexp('SIM1_T-1-0.000010.cas.gz', '(.*-[^-]*-)([0-9]\.[0-9]*)(.*)', 'tokens', 'once')

tokens = 

    'SIM1_T-1-'    '0.000010'    '.cas.gz'

In my experience, the sscanf function will not work with a mix of numeric and alphanumeric data.

Upvotes: 1

Related Questions