Search code examples
regexmatlabregexp-replace

MATLAB regexprep with parentheses


Given a cell array of strings:

CellArray={'(first)';'second';'x(third)';'four)'; '(...)'};

I would like the following result:

newCellArray={'first';'second';'x(third)';'four)';'...'};

i.e. I would like to remove the parentheses only if they are at the start and end of the word...

I would like to use something like:

newCellArray = regexprep(CellArray,expression,replace);

But sadly, I did not succeed despite many attempts...


Solution

  • You can use the beginning and end anchors with a token capture and a back-replace:

    >> expr = '^\((.+)\)$';
    >> CellArray = {'(first)';'second';'x(third)';'four)'; '(...)'};
    >> newCellArray = regexprep(CellArray,expr,'$1')
    
    newCellArray = 
    
        'first'
        'second'
        'x(third)'
        'four)'
        '...'