read a particular string from a line in text file

2 次查看(过去 30 天)
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 ?

采纳的回答

Tom Wright
Tom Wright 2015-9-2
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by