Matlab如何在三维数组上使用正则表达式?

时间:2016-11-24 09:52:49

标签: arrays regex matlab

我的功能是一个文本文件'在'并返回一个文件,其中所有4个字母的单词替换为' ****。'到目前为止,我已经设法得到一个3d数组,每个单元格为1个字。如何将所有4个字母单词转换为' ****?'

%in.txt =

     %word words
     %words words words word
     %words
     %word word word



fid = fopen(in);

tline = fgetl(fid);
string = {''};
while ischar(tline)%create an array where each cell is 1 line
    string(length(string)+1) = {tline};
    tline = fgetl(fid);
end

str = {''};
for x=2:length(string)%create a matrix where each cell is is 1 line with each of those cells being 1 word
    str(x) = {split(string(x), ' ')};
    end
end

1 个答案:

答案 0 :(得分:1)

使用regexprep

fid = fopen('in.txt', 'r');

% (when running in a function)
%OC = onCleanup(@() any(fopen('all')==fid) && fclose(fid));

data = regexprep(data{1}, ...
                 '\<(?:[-A-Za-z]{4})([^-A-Za-z]|$)',...
                 '****$1');            

fclose(fid);