Write a function to extracts number between 2 letters?

조회 수: 3 (최근 30일)
Mohammed
Mohammed 2016년 9월 7일
댓글: Guillaume 2016년 9월 8일
I am trying to write a MATLAB code that extracts a 3 digit number in between two letters. the tricky part is that the letter after the number could be either (s)or(h)
E.g 1 the filename is 'rfc_f123sars.tif' this should extract 123 which is between _f and s E.g 2 the filename is 'rfc_f456hars.tif' this should extract 456 which is between _f and h Thanks :)

채택된 답변

per isakson
per isakson 2016년 9월 7일
편집: per isakson 2016년 9월 7일
Without comments
>> str = 'rfc_f123sars.tif' ;
>> regexp( str, '(?<=_f)\d{3}(?=[sh]{1})', 'match', 'once' )
ans =
123
and slightly different; replace [sh]{1} by (s|h), which is a tiny bit cleaner
>> str = 'rfc_f456hars.tif';
>> regexp( str, '(?<=_f)\d{3}(?=(s|h))', 'match', 'once' )
ans =
456
If regexp returns empty set out=0
  댓글 수: 4
Mohammed
Mohammed 2016년 9월 7일
thank you :) :)
Guillaume
Guillaume 2016년 9월 8일
Note that [sh]{1} is exactly the same as [sh]

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

추가 답변 (2개)

Walter Roberson
Walter Roberson 2016년 9월 7일
regexp(filename, '\d\d\d', 'match')
or if you want to be more secure,
regexp(filename, '(?<=[A-Za-z])\d\d\d(?=[A-Za-z])', 'match')

Guillaume
Guillaume 2016년 9월 7일
편집: Guillaume 2016년 9월 7일
This is trivial with a regular expression:
nstr = regexp(filename, '(?<=_f)\d+(?=(s|h))', 'match', 'once');
if isempty(nstr)
n = 0;
else
n = str2double(nstr);
end
The regular expression matches a sequence of one or more digit, preceded by _f, followed by h or s.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by