如何使用正则表达式在单元格数组中查找以某个子字符串开头和结尾的字符串?

时间:2014-03-19 13:22:33

标签: regex matlab

考虑以下包含文件名的字符串单元格数组:

A = { 'abcout.txt';
      'outabcd.txt';
      'outabcef.png';
      'outout.txt' }

我想找到所有.txt - 以" out" 开头的文件。

我可以这样做:

filenames = regexp( A ,'out\w*.txt');
filenames = A( cellfun(@(x) ~isempty(x) && x == 1,filenames) )

返回所需的输出:

filenames = 

    'outabcd.txt'
    'outout.txt'

但我想知道如何使用regexp跳过cellfun步骤?

以下几乎可行:

filenames = regexp( A ,'out\w*.txt','match');
filenames = [filenames{:}]'

但它也返回第一个字符串,该字符串无效(甚至没有正确显示):

filenames = 

    'out.txt'
    'outabcd.txt'
    'outout.txt'

如何修改:'out\w*.txt'

3 个答案:

答案 0 :(得分:2)

使用^锚定在字符串的开头,并使用$在字符串的末尾。

filenames = regexp( A ,'^out\w*.txt$');

目前您从文字out.txt获得abcout.txt,因为您没有使用anchor

答案 1 :(得分:2)

就个人而言,我会将其修改为

'^out.*\.txt$'

因为\w*排除了

之类的内容
'out file.txt'

我认为应该包含...此外,原始字符串不正确,因为它也匹配

'outFileWtxt'

因为您没有转义.元字符:)

无论如何,从表演的角度来看,摆脱cellfun实际上并不是你想要的;你应该正确使用它:

%// dummy data
A = { 'abcout.txt';
      'outabcd.txt';
      'outabcef.png';
      'outout.txt' };

%// Make sure we have something substantial to do
A = repmat(A, 1e5,1);

%// New way   
tic
    F = regexp(A, '^out.*\.txt$', 'match');
    F = [F{:}];
toc

%// Old way with optimized cellfun() call
tic
    F = regexp(A, '^out.*\.txt$');
    F = A(~cellfun('isempty', F));
toc

结果:

Elapsed time is 0.928403 seconds. %// without cellfun
Elapsed time is 0.471774 seconds. %// with optimized cellfun

cellfun的此调用更快,因为字符串选项引用cellfun二进制文件中的特定硬编码函数。这比任何匿名函数都快很多,因为 必须在MATLAB环境中进行评估。

答案 2 :(得分:1)

试试这个正则表达式: ^ - 行开头的状态

^out\w*.txt