MATLAB Answers

extracting dates within a text

3 views (last 30 days)
Sadegh Nabavi
Sadegh Nabavi on 30 Nov 2019
Commented: Sadegh Nabavi on 30 Nov 2019
Good day all,
I have a csv file with texts and and dates mixed in each cell. I need to extract the dates that follow a specific text and store them in cell arrays. Example: "MovExperiment/MovingBarParameters started at 2018-04-17_09-32-11"; please see highlighted cells in the attached image.
What is the efficient way to do this?

  1 Comment

dpb on 30 Nov 2019
Dunno and can't experiment without a copy of the significant portion of the file to look at.
Attach a (smallish) section of the file, not an image.

Sign in to comment.

Accepted Answer

dpb on 30 Nov 2019
Edited: dpb on 30 Nov 2019
matchstr='LoomingExp'; % string to match
c=textread('book1.csv','%s','delimiter',''); % read as cellstr array
c=char(c(contains(c,matchstr))); % save those with matching string/convert to char array
dt=datetime(c(:,end-18:end),'InputFormat','yyyy-MM-dd_HH-mm-ss'); % convert date strings to datetime
textread has been deprecated by TMW, but it's still useful in being able to do many things without the bother of having to have a file handle but using the filename directly.


Sadegh Nabavi
Sadegh Nabavi on 30 Nov 2019
Thanks a lot. The only change I needed to make to your script is to insert:
c = cellfun(@(c) c(end-18:end), c, 'un', 0);.
Otherwise, I get the error message:
Error using datetime (line 636)
Unable to convert the text to datetime using the format 'yyyy-MM-dd_HH-mm-ss'.
c = cellfun(@(c) c(end-18:end), c, 'un', 0);
dpb on 30 Nov 2019
Oh. I had done char() to convert to character array at command line but missed it when cut and pasted...
Updated Answer
Sadegh Nabavi
Sadegh Nabavi on 30 Nov 2019
Thanks a lot. It works smoothly.

Sign in to comment.

More Answers (0)

Sign in to answer this question.