Mathias Kure
Mathias Kure

Reputation: 33

Reading number from string containing ' '

I would like to read the number 2 from the following char:

'mc_parameters.E_i = '2';'

So far, the ' ' around the number makes it a mess, because what MATLAB sees when I try to use sscanf, textscan and str2num is

'mc_parameters.E_i = '2';'

and it doesn't recognize the last ';' as a string in itself.

Any ideas?

Upvotes: 0

Views: 94

Answers (3)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

I don't quite understand what you mean, but this one-liner works for all interpretations of your question I could think of (and then some):

cellfun(@str2double, regexp(str, ...
    '[+-]?[0-9]+\.?[0-9]*(e|E|d|D)?[+-]?[0-9]*', 'match'));    

where str is your string to extract the number from.

This regular expression will find and convert all numbers in the string, in any of the following forms:

  • 2
  • +2.05
  • 21.05
  • -2.0755e-4
  • -0.0755D4
  • ...

NOTE: if you only need to extract integers, a simple '[0-9]*' will suffice :)

Examples:

>> format short e
>> f = @(str) cellfun(@str2double, regexp(str, '[+-]?[0-9]+\.?[0-9]*(e|E|d|D)?[+-]?[0-9]*', 'match'));
>> 
>> str = 'mc_parameters.E_i = ''2.04'';  +-8.4e-005';
>> f(str)
ans = 
    2.0400e+000    -8.400e-005

>> str = '2.18';
>> f(str)
ans = 
    2.1800e+000

>> str = '''2.21''; ''2..3e-4';
>> f(str)
ans = 
    2.2100e+000    2.0000e+000    3.0000e-004

Upvotes: 0

Hichem
Hichem

Reputation: 1182

you gave to use str2num

str = '2';

x = str2num(str) 

output

x = 2;

Upvotes: 0

Vuwox
Vuwox

Reputation: 2359

Just use this functon :

myNum = str2num(myString);

The documentation about str2num

EDIT

I miss understood something there another thing to add :

myString = 'mc_parameters.E_i = '2';';
temp = sscanf(myString,['%[A-z.] %3c %d']);
extractNumberInString = temp(end); % Because last scanf is %d for double number.

Maybe you need to convert myString like this to execute the example :

myString = 'mc_parameters.E_i = ''2'';';

EDIT 2

Better solution is to use textscan because with %* you can skip some char like this :

test = textscan(myString,'%*[^''] %*c %d'); 
% Search until first ' and look for the white space and finish with the double number

Upvotes: 1

Related Questions