Search code examples
matlabpattern-matchingstring-matchingtext-processingtextscan

how to find negative and positive number from a string?


I've a set of chemical reactions, and I need to read only the first number of each chemical. For example, I've a string as

reaction = '-1.0CdCl2(aq)  1.0Cd++  2.0Cl-';

I want the find -1.0 of CdCl2(aq), 1.0 of Cd++, and 2.0 of Cl-.


Solution

  • textscan works here (assuming white-space delimiting the reactants):

    >> C = textscan(reaction,'%f%s')
    C = 
        [3x1 double]    {3x1 cell}
    >> C{1}' %' decimals not shown
    ans =
        -1     1     2
    >> C{2}
    ans = 
        'CdCl2(aq)'
        'Cd++'
        'Cl-'
    

    Also assuming reaction starts with a number.