2013-12-10 359 views
1
diary_file = tempname(); 
diary(diary_file);   
myFun(); 
diary('off');    
output = fileread(diary_file); 

我想搜索一个字符串从output,但也忽略空格和上/下情况。下面是什么在output一个例子:忽略空格和个案MATLAB


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

我怎么能忽略空格和案例从output

回答

2

假设你是不是太担心一不小心匹配是这样的:'thetEst:passed'这里是你可以做什么:

删除所有的空格,只有比较低的情况下

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

这将返回

found = 

withspaces 

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

+0

我必须在输出日志上做到这一点 – lola

+0

found ='thetest:passed'然后当我在输出中搜索时,我还需要忽略输出中的空格... – lola

+0

@lola然后还使用'output = lower(output(output〜=''))' –

0

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

+0

我已经更新了这个问题,我可以忽略所有空格 – lola

0

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

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

如果你不关心那里的比赛,但只发生,如果有比赛在所有的位置,删除所有空格将是一个蛮力,而且有些讨厌,可能性:

a = strfind(strrrep(output, ' ',''), found); 
+0

我想你会想使用'regexpi'而不是'regexp'。 –

+0

a = regexpi(输出,'\ s * test \ s *:\ s * passed')会返回一个1x2double? – lola

+0

@ DennisJaheruddin,对。固定。 – sebastian

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} 

对于更一般的情况。

+0

当然'regexp'更灵活,并且不是很慢。但通常在使用strfind时速度更快。对于空间字符的稳健性仍然+1。 –