忽略空格和案例MATLAB

时间:2013-12-10 14:35:51

标签: matlab

diary_file = tempname();
diary(diary_file);         
myFun(); 
diary('off');             
output = fileread(diary_file);

我想从output搜索字符串,但也要忽略空格和大/小写。以下是output中的内容示例:


the test  : passed 
number : 4

found = 'thetest:passed'
a = strfind(output,found ) 

如何忽略output中的空格和案例?

4 个答案:

答案 0 :(得分:2)

假设你并不担心意外匹配如下:'thetEst:passed'这就是你可以做的事情:

删除所有空格,仅比较小写

found = 'With spaces'
found = lower(found(found ~= ' '))

这将返回

found =

withspaces

当然,您还需要对每行输出执行此操作。

答案 1 :(得分:2)

另一种方式:

regexpi(output(~isspace(output)), found, 'match')

如果output是单个字符串,或

regexpi(regexprep(output,'\s',''), found, 'match')

更常见的情况(class(output) == 'cell' 'char')。

优点:

  • 快速。
  • 健壮(除去所有空白(不仅仅是空格))
  • 更灵活(你可以返回匹配的开始/结束索引,标记化等)
  • 将返回输出中匹配的原始案例

缺点:

  • 更多打字
  • 不太明显(需要更多文档)
  • 将在输出中返回匹配的原始情况(是的,该硬币有两面)

两个列表中的最后一点很容易使用lower()upper()强制降低或大写,但如果你想要相同的情况,那就更多了:

C = regexpi(output(~isspace(output)), found, 'match');
if ~isempty(C)
    C = found; end

表示单个字符串,或

C = regexpi(regexprep(output, '\s', ''), found, 'match')
C(~cellfun('isempty', C)) = {found}

更一般的情况。

答案 2 :(得分:0)

您可以使用lower将所有内容转换为小写以解决您的案例问题。然而,忽略你想要的空白是有点棘手。看起来你想要保留一些空格但不是全部,在这种情况下你应该用空格分割字符串并逐个比较子字符串。

答案 3 :(得分:0)

我会使用正则表达式做广告,例如像这样:

a = regexpi(output, 'the\s*test\s*:\s*passed');

如果你不关心匹配发生的位置,但只有完全匹配,删除所有空格将是一种蛮力,有点讨厌,可能性:

a = strfind(strrrep(output, ' ',''), found);
相关问题