Matlab开关+正则表达式

时间:2019-05-29 13:23:37

标签: regex matlab

我试图阅读这篇文章,但我认为我可能会从根本上走错路。这就是我想要的:

  • 我的用户输入值无法预测,例如a='test1'可能相差很大
  • 我想测试输入字符串的不同场景,其中所有定义的场景都应进行一些模糊匹配,但如果不适用,则应恢复为默认值

所以理想情况下,我认为我想要这样的案例结构:

a='test1';
switch a
  case ~isempty(regexpi(a,'test','match','once')) %should handle all cases where 'test' is contained in the input string
    disp('this');
  otherwise %should handle everything else
    disp('that');
end

但它总是输出that

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您正在使用 char (字符数组)a作为切换变量和 logical (是/否) )表达式结果,否则将始终使用否则,因为 char 不是 logical

您可以将逻辑表达式结果用作切换变量,并以true为例:

a='test1';
switch ~isempty(regexpi(a,'test','match','once'))
  case  true %should handle all cases where 'test' is contained in the input string
    disp('this');
  otherwise %should handle everything else
    disp('that');
end

或仅使用if-else语句:

a='test1';
if ~isempty(regexpi(a,'test','match','once'))
    disp('this');
else %should handle everything else
    disp('that');
end

答案 1 :(得分:1)

如所写,您正在将布尔表达式的结果与要测试的值a进行比较。这永远不会匹配,因此只需使用switch true即可。

按顺序评估案件,因此等效于使用

if ...
    % Do something
elseif ...
    % Do something else
else
    % Otherwise
end

有人可能会争辩的结构是可取的。