正则表达式中的平衡括号

时间:2014-03-18 20:16:54

标签: regex string matlab

如何在Matlab中找到字符串中的最大可能模式,该模式与某些表达式匹配。示例将阐明我的意思:

str = 'tan(sin*cos)';
str = 'tan(sin(exp)*cos(exp))';

我想找到类似tan(\w*)的模式。但我想要tan中的括号进行平衡。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

没有反复使用的正则表达式,这是不可能的。例如,这个字符串:

str = 'tan(tan(tan(x) + 4) + cos(x))'

必须是从内到外的正则表达式""只有递归才能做到的事情。

相反,我只是使用更实用的解决方案:

regexprep(str, 'tan', '')

和/或在必要时进一步分割。或者,正如Ruud已经建议的那样,只需使用一个循环:

str{1} = 'tan(x)';
str{2} = 'tan(sin(exp)*cos(exp)) + tan(tan(x) + 4)';

S = regexp(str, 'tan\(');
match = cell(size(str));
[match{:}] = deal({});
for ii = 1:numel(str)
    if ~isempty(S{ii})
        for jj = 1:numel(S{ii})

            open  = false;
            start = S{ii}(jj)+4;
            for kk = start : numel(str{ii})            
                switch str{ii}(kk)
                    case '('
                        open = true;
                    case ')'
                        if open
                            open = false;
                        else
                            match{ii}{end+1} = str{ii}(start:kk-1);
                            break;
                        end
                end
            end
        end
    end
end