Using RegEx (strrep) on CharArray with For Loop
3 views (last 30 days)
Show older comments
Hello. I have a series of dates that need to be reformatted as such:
From:
2007-04-22 01:04:21.000
2007-05-10 01:08:48.000
2007-06-15 22:03:31.000
To:
2007/04/22 01:04:21
2007/05/10 01:08:48
2007/06/15 22:03:31
I currently have this loop to try and replace each "-" with "/". (I also need to cut off the ".000", but I have not gotten to that yet.)
newTimes = get(c, 'START_STR');
for j = 1 : size(newTimes, 1);
fprintf('Looped'); %Just for testing
newsTimes(j) = strrep(newTimes(j), '-' ,'/')
end
However this does not work.
I am no longer getting an error that "Error using ==> strrep Input strings must have one row". Which I had before I put it in a loop. But my output is still wrong.
It does NOT make the swap of '-' for "/" and it also prints out the array for each time the loop runs, as opposed to printing one line for each run of the loop.
Any ideas? Ideally I would like to find a function similar to strrep that can be used in an array... otherwise a way to fix the loop would be great.
My Output looks Like this:
Looped
newstationtimes =
2007-04-22 01:04:21.000
2007-05-10 01:08:48.000
2007-06-15 22:03:31.000
... rest of list
Repeated like 40 times.
5 Comments
Daniel Shub
on 29 Apr 2013
@Cedric just because you don't need regexp, doesn't mean you cannot use it. I bet you would get a vote for a regexp answer.
Cedric
on 29 Apr 2013
Edited: Cedric
on 29 Apr 2013
Well, I'd personally go for a reshape of the char. stream into a ?x25 array (or 23/24 if \r and or \n are not present), then a replacement like buffer(buffer=='-') = '/', and finally I'd kill columns 20 to 23.
Regexp are useless because of the rigid structure, but if the time format was more flexible or if there was text with variable length between the date and the time, one way to use pattern matching would be:
content = fileread('myFileWithTimeStamps.txt') ;
content_new = regexprep(content, '(.{4})-(..)-(.*?)\.000', '$1/$2/$3') ;
Accepted Answer
Daniel Shub
on 29 Apr 2013
What about
datestr(['2007-04-22 01:04:21.000';'2007-05-10 01:08:48.000';'2007-06-15 22:03:31.000'], 'yyyy/mm/dd HH:MM:SS')
I think some of the date functions are slow (if so Jan will probably chime in with the faster way) ...
More Answers (1)
Sean de Wolski
on 29 Apr 2013
Edited: Sean de Wolski
on 29 Apr 2013
Two easy ways:
If the data is indeed all column-aligned, how about:
data(:,[5 8]) = '/'
data = data(:,1:end-4);
If the data is not perfectly column aligned:
- Converting them to date numbers with datenum() and the format that you have?
- Convert them back to a string using datestr() with your choice output format?
This surely won't be the fastest way.
See Also
Categories
Find more on Dates and Time 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!