How can I use regexp to total the amount of lines containing a certain word.
2 views (last 30 days)
Show older comments
I have a file with multiple lines ending with the words "valid" or "corrupted" and I am attempting to calculate the total number of lines that contain the word "valid". I have been trying to do so using regexp but have currently only been able to receive 0 as the amount of lines that contain this word. How can I use regexp to find all the lines with valid at the end?
3 Comments
Sean de Wolski
on 19 Nov 2013
By multiple lines, do you mean an nx1 cell array, an mxn char array or an mx1 char array with '\n's?
Answers (1)
Walter Roberson
on 20 Nov 2013
while true
validline = fgetl(fid);
if ~ischar(validline); break; end
if regexp(validline, '(valid)', 'match');
valid{end+1,1} = validline;
end
end
fprintf('Number of valid lines: %d %n', numel(valid))
5 Comments
Walter Roberson
on 20 Nov 2013
FileContents = fileread('TheFileName.txt');
count = length(regexp(FileContents, 'valid'));
See Also
Categories
Find more on String Parsing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!