How to get general interval from a string with regexp

조회 수: 5 (최근 30일)
Micke Malmström
Micke Malmström 2020년 2월 5일
답변: fred ssemwogerere 2020년 2월 5일
I have a long string (FileName) from which I would like to extract some variables describing the X values. The string contins this format:
"... X 1.5-2.8 mm ... "
from which I successfuly can extract the range (from 1.5 to 2.8) with:
[v,vv]=regexp(FileName,[' X ([\d\.]){1,10}-([\d\.]){1,10} mm'],'tokens','match');
However, when the range includes a minus sign this does not work very well...
I've tried including the minus sign like this:
[v,vv]=regexp(FileName,[' X ([-\d\.]){1,10}-([-\d\.]){1,10} mm'],'tokens','match');
But that will for example give me (if FileName contains "-1.5-2.8") a range of from "-1.5-" to "2.8".
How can I get this line of code to work with these formats:
X 4--8 mm (where the range is from 4 to -8 mm)
X -4-8 mm
X -4--8 mm
or do I need to make a regexp for each of these cases separately?

답변 (2개)

Micke Malmström
Micke Malmström 2020년 2월 5일
Seems this works ok:
[v,vv]=regexp(obj.FileName,[' X ([-\d\.]){1,10}-([-\d\.]){1,10} mm'],'tokens','match');
if ~isempty(v) % check for negative last value which gives the responce: v{1}={'2.8-','4.3'}
if strcmpi(v{1, 1}{1, 1}(end),'-')
v{1, 1}{1, 2}=['-' v{1, 1}{1, 2}];
v{1, 1}{1, 1}= v{1, 1}{1, 1}(1:end-1);
end
end

fred  ssemwogerere
fred ssemwogerere 2020년 2월 5일
Hello, making use of your string, with some modification, this should do nicely:
str="... X 1.5-2.8 mm X -2.5--3.3 mm... ";
expression = '(X \W*\d.{2})-(\W*\d.{5})';
myday=regexp(str,expression,'tokens'); % all matching strings will be stored in a cell array
% you can then use "strjoin" for each item of the cell array to get desired output for example:
val=strjoin(myday{1,1});

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by