2016-11-24 48 views
1

我有一個函數給出了一個文本文件'in',並返回一個文件,其中所有4個字母的單詞都替換爲'****'。到目前爲止,我已經設法得到一個3d數組,每個單元格爲1個字。如何將所有4個字母的單詞變成'****?'Matlab如何在3維數組上使用正則表達式?

%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 
+0

使用'regexprep(STR, '\ <[A-ZA-Z] {4} \>', '****')' – obchardon

回答

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); 
+0

是否有一種保持文字如完好再見的方式? –

+0

@JakeDorin是的,看我的更新 –

相關問題