How to use regex to obtain double values?

조회 수: 37 (최근 30일)
Struggling in MATLAB
Struggling in MATLAB 2022년 7월 29일
댓글: Struggling in MATLAB 2022년 7월 29일
I have an array of strings which contains some units. I have attahced the array.
unq = ["10 lux";"10lux";"15";"15.0";"15.5 Lux";"15luX";"15lux";"20lux";"36lux";"42lux";"9lux"]
They are put in different format on different days. So, I get 11 unique entries. I used the following code only to keep the numeric part.
trimData = strtrim(unq);
regexData = regexp(trimData,'\d*','Match');
cleanedData = cell(numel(unq),1);
for kk = 1:numel(unq)
if length(regexData{kk}) >= 1
cleanedData{kk} = regexData{kk}(1);
end
end
cleanedData = str2double(string(cleanedData));
I got
cleanedData = [10;10;15;15;15;15;15;20;36;42;9]
I am not getting 15.5 in the resulting array. How do get the numbers in which the digits after decimal place is not '0'? How do I write a regular expression for that?

채택된 답변

Walter Roberson
Walter Roberson 2022년 7월 29일
편집: Walter Roberson 2022년 7월 29일
Extending to the possibility of fraction values that start with decimal point (with no leading zero), and extending to support negative values
But not extending to exponential format:
unq = ["10 lux";"-10lux";"15";"15.0";"15.5 Lux";"15luX";"15lux";"20lux";"36lux";"42lux";".9lux"]
unq = 11×1 string array
"10 lux" "-10lux" "15" "15.0" "15.5 Lux" "15luX" "15lux" "20lux" "36lux" "42lux" ".9lux"
regexData = regexp(unq, '(-?\d+(\.\d*)?)|(-?\.\d+)', 'match', 'once')
regexData = 11×1 string array
"10" "-10" "15" "15.0" "15.5" "15" "15" "20" "36" "42" ".9"
  댓글 수: 1
Struggling in MATLAB
Struggling in MATLAB 2022년 7월 29일
Exactly what I needed. Thanks a lot, Walter!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by