Search code examples
matlabsortingregexp-replace

Use of regexprep in MATLAB to remove characters within parentheses in MATLAB


I want to remove characters within parentheses from a string in MATLAB:

For eg: I have the string S(+42.01)DKHDKPDISEVTKFDKSKLKKTETHEKNPLPTKETIDQEKQG but want to remove the parentheses and store : SDKHDKPDISEVTKFDKSKLKKTETHEKNPLPTKETIDQEKQG

The characters in parentheses could be text, numbers, combination of text numbers and special characters. Also the parentheses can occur multiple times in the same string.

Thanks


Solution

  • There you go:

    x = 'Q(-17.03)VAQMHVWRAVNHDRNHGTGSGRH(-.98)';
    y = regexprep(x, '\([^\(\)]*\)',''); % detect substring formed by 
        % parentheses and anything in between that is not a parenthesis,
        % and replace that by an empty string
    

    gives

    y =
    QVAQMHVWRAVNHDRNHGTGSGRH