How to search a number in a random string?
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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') %
0 comentarios
Respuestas (2)
madhan ravi
el 14 de Jul. de 2020
Editada: madhan ravi
el 14 de Jul. de 2020
str = str2double(regexp(text,'\d+$','match'))
3 comentarios
madhan ravi
el 14 de Jul. de 2020
Thanks Stephen ;). Sometimes MATLAB mobile gives wierd answer if the internet connection is not good.
Leon
el 12 de Abr. de 2024
How would you adjust this to allow miscellaneous text after the number too, e.g. "thv123_gdf" => 123? Thanks.
Rohit Anand
el 14 de Jul. de 2020
Editada: Rohit Anand
el 14 de Jul. de 2020
You can do it all in a few steps for better understanding.
- Use regexp to get the index from where we need to slice the string. (In the below example you will get index of '1').
- Slice the string from idx onwards to get the number at the end of the string.
- 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 comentarios
Stephen23
el 14 de Jul. de 2020
"How does it differ from the answer I gave?"
More complex for no obvious benefit.
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!