问题
I'd like to clear all variables from workspace, but with some exceptions defined by regular expressions.
The function clear
has an additional option -regexp
clear -regexp expr1 ... exprN
clears all variables that match any of the regular expressions listed. This option only clears variables.
So I'm looking for the opposite.
Also there is
clearvars -regexp p1 p2 ...
clears all variables that match regular expression patterns p1, p2, and so on.
clearvars -except v1 v2 ...
clears all variables except for those specified following the -except flag.
Which is already quite nice for complete variable names, but not working for regexp like the first option.
There are solutions on FEX, but I don't want to use additional custom functions.
But As there are such convenient solutions for the just slightly different cases above, I wonder if there is also a simple way to do:
keep -regexp expr1 ... exprN
with inbuilt functions.
回答1:
Take a look at this for inverse regexp matching. In this context:
clear -regexp ^((?!expr1|expr2|...).)*$
clearvars
is not built-in, but an m-function, which has its own disadvantages. With the inverse regexp matching, you can do everything with clear
(a built-in).
来源:https://stackoverflow.com/questions/20073383/clear-variables-from-workspace-with-exceptions-by-use-of-regular-expressions