How can I use regexp to total the amount of lines containing a certain word.
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
Azzi Abdelmalek
on 19 Nov 2013
Show your code
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?
Kevin
on 19 Nov 2013
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
Kevin
on 20 Nov 2013
Walter Roberson
on 20 Nov 2013
Try using 'valid' instead of '(valid)' -- though in theory that should not matter in a regular expression.
Kevin
on 20 Nov 2013
Walter Roberson
on 20 Nov 2013
FileContents = fileread('TheFileName.txt');
count = length(regexp(FileContents, 'valid'));
Kevin
on 20 Nov 2013
Categories
Find more on Characters and Strings 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!