Search code examples
regexmatlabintegernegative-number

Allow negative integers for Regular Expressions in MATLAB


Does regular expressions in MATLAB take it a negative integer, such as "-1". My code doesn't seem to run well due to this error "Index exceeds matrix dimensions." and i know it has something to do with the negative values in my data file. It shows the negative integer in the workspace window.

Any ideas as to how i can allow negative integers in my regular expression

Here's the code:

       m = regexp(value, 'START=(\d+)', 'tokens');
       m2 = regexp(value, 'STOP=(\d+)', 'tokens');

       start = cell2mat(m{1});
       stop = cell2mat(m2{1});


       % Print result
       fprintf(fout, 'INSERT INTO cath_domains (pdbcode, cathbegin, cathend) VALUES("%s", %s, %s)\n', domain, start, stop);

Solution

  • The token (\d+) will only return numbers, not characters like the minus sign. Thus, if there is a minus sign, there is no match, m and/or m2 are empty, and thus you're getting an error when you try to index into the cell arrays.

    Try

    m = regexp(value, 'START=(-?\d+)', 'tokens');
    

    instead, which allows for an optional minus sign.