2014-10-08 44 views

回答

1
getPart = @(str, c) str2double(['0' regexp(str, ['\d*(?=' c ')'], 'match', 'once')]); 

str = 'PT36S'; 
seconds = getPart(str, 'S'); 
minutes = getPart(str, 'M'); 
hours = getPart(str, 'H'); 

這會查找字符c,找到它後面的數字並將它們轉換爲double。它在開頭添加字符'0',因爲如果regexp找不到匹配項,它將返回一個空字符串。添加這個將空字符串轉換爲零而不影響其他數字。如果您想將其限制在PT之後的部分,您可以使用原始字符串刪除該部分

str = regexprep(str, '^.*PT', ''); 
+0

感謝您的幫助! – Thoth 2014-10-08 20:21:27

1

使用datevec將代表小時,分鐘等的字符串轉換爲相應的數值。請參閱「幫助datestr」以瞭解datevec第二次輸入中使用的符號的規則,即。格式字符串。以下是如何轉換給出的兩個示例,我將它留給您來擴展它以涵蓋整個格式。

str = 'PT36S'; 
str = strrep(str, 'PT', ''); % PT have to go. 
if ~ismember('M', str) 
% To use a single format string, we must write zero minutes if none are there already 
str = ['00M', str]; 
end 

% Date string cannot contain characters y,m,d,H,M or S, so remove these 
str = strrep(str, 'S', ' '); 
str = strrep(str, 'M', ' '); 

% Call datevec with appropriate format string 
[~, ~, ~, ~, min, sec] = datevec(str, 'MM SS') 

您可以擴展這個來管理小時,日子等,通過包含額外的if循環類似於上面的循環。除了給出的例子,我對這個標準並不熟悉,所以讓我知道它是否不那麼簡單。