How to search a number in a random string?

조회 수: 6 (최근 30일)
Josy M
Josy M 2020년 7월 14일
댓글: Leon 2024년 4월 12일
Hello :)
This time just a short question: I have random strings with characters and numbers. I (need) want to extract the number at the end of the string. The string consists evertime with some characters at the beginng and at the end a number. How does it work to get the number?
((( For me its difficult because i dont know how many characters are the beginning and i dont know how long the number is)))))
I saw this command. But i dont know to use it exactly.
text="tq3" %->3
text="v023"%->23
%or
text="ABCDEFRANDOM1234" %->1234
str=regexp(text,'(??????', 'match') %

답변 (2개)

madhan ravi
madhan ravi 2020년 7월 14일
편집: madhan ravi 2020년 7월 14일
str = str2double(regexp(text,'\d+$','match'))
  댓글 수: 3
madhan ravi
madhan ravi 2020년 7월 14일
Thanks Stephen ;). Sometimes MATLAB mobile gives wierd answer if the internet connection is not good.
Leon
Leon 2024년 4월 12일
How would you adjust this to allow miscellaneous text after the number too, e.g. "thv123_gdf" => 123? Thanks.

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


Rohit Anand
Rohit Anand 2020년 7월 14일
편집: Rohit Anand 2020년 7월 14일
You can do it all in a few steps for better understanding.
  1. Use regexp to get the index from where we need to slice the string. (In the below example you will get index of '1').
  2. Slice the string from idx onwards to get the number at the end of the string.
  3. Convert the obtained numeric string into a double, using str2double
text="ABCDEF78RAN9DOM1234";
idx = regexp(text, '\d+$'); % Find the first index of the number
y = extractAfter(text, idx-1); % Slice the string
number = str2double(y) % convert to double
  댓글 수: 2
madhan ravi
madhan ravi 2020년 7월 14일
How does it differ from the answer I gave?
Stephen23
Stephen23 2020년 7월 14일
"How does it differ from the answer I gave?"
More complex for no obvious benefit.

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

카테고리

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