read a particular string from a line in text file

1 view (last 30 days)
Lets say I have two lines in a text file like this:
The value of the number is 240.56 units.
The value of the number is 140.43 units.
I want to read only the values (240.56 and 140.43) from those lines. However there are many such lines in the similar format inside the text file. So i can't go by comparing string value and then read that value. How to read those dynamic values which are located in a sentence at a particular position. Any ideas ?

Accepted Answer

Tom Wright
Tom Wright on 2 Sep 2015
Sounds like a regular expression is the way to go.
fid = fopen('YourFile.txt','rt');
expression = '([\d.]+)' % matches one or more digits and .
% a more advanced expression is (\d+(?:\.\d*)?|\.\d+)
while true
thisline = fgetl(fid);
value = regexp(thisline,exp,'match'); % perform the regular expression
value = value(0);
end

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!