Using regular expressions to identify names and unit from string

Hello,
I have the following strings
'name1/name2 [°C]'
'name1/name2 [kW]'
'name1/name2 [%]'
or
'name1/name2 {0,1}'
or
'name1/name2'
How can I use regular expressions to find the names and the unit, if there is any?
Thanks!

 채택된 답변

jonas
jonas 2018년 7월 17일
편집: jonas 2018년 7월 17일
You could do it in two steps, like this:
str='name1/name2 [C]'
%%Extract unit, if there is one
exp=']|[|}|{';
id=regexp(str,exp);
if isempty(id)==0
unit=str(id(1)+1:id(2)-1)
end
%%Extract name
exp='/| ';
id=regexp(str,exp);
if numel(id)==2
name1=str(1:id(1)-1)
name2=str(id(1)+1:id(2)-1)
else
name1=str(1:id(1)-1)
name2=str(id(1)+1:end)
end
If you do not want to save whatever is within the curly brackets as units, then remove those from the first expression.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Text Data Preparation에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

2018년 7월 17일

편집:

2018년 7월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by