Get values within string with special characters

Hi all,
I have a column of strings such as these. My desired output will be two columns for each respective set of numbers
"
*58477$265#"
It's newline, new line and an asterisk. I am trying to get both sets of numbers (between *..$ and $..#). I could not get sscanf or extractAfter to work for this case. Any suggestions?

5 comentarios

The answer is going to necessarily be specific to your data. Please share your data by saving your variable to a mat file and attaching it to your post using the paperclip icon.
per isakson
per isakson el 12 de Abr. de 2023
Editada: per isakson el 12 de Abr. de 2023
"I have a column of strings such as these." Is that in a text file or a variable? In either case it can be done with regexp()
str = sprintf("\n\n*58477$265#"); % sample data
str = [str;str];
cac = regexp( str, '\n\n\*(\d+)\$(\d+)\#', 'tokens' );
cac{1}{:}
ans = 1×2 string array
"58477" "265"
(and possibly with textscan() or some newer text reading function)
str = sprintf("\n\n*58477$265#"); % sample data
str = [str;str];
parts = regexp(str, '\d+', 'match')
parts = 2×1 cell array
{["58477" "265"]} {["58477" "265"]}
%in the special case where there are exactly two matches
vertcat(parts{:})
ans = 2×2 string array
"58477" "265" "58477" "265"
Note: textscan() can only handle a string scalar or a character vector (not a character array), so it cannot directly be used in this situation, at least not without looping or arrayfun()... though you could potentially join() the strings to make one long string that you could process with textscan()
One more hint
str = sprintf("\n\n*58477$265#"); % sample data
extractBetween( str, "*", "$" )
ans = "58477"
extractBetween( str, "$", "#" )
ans = "265"
and it's nothing wrong with loops if your column isn't HUGE and execution time becomes a problem.

Iniciar sesión para comentar.

Respuestas (1)

dpb
dpb el 12 de Abr. de 2023
Movida: dpb el 12 de Abr. de 2023
str = sprintf("\n\n*58477$265#"); % sample data
str = [str;str];
Carrying on in the same vein with some of the newer stuff...
str2double(extract(str,digitsPattern))
ans = 2×2
58477 265 58477 265

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Productos

Versión

R2023a

Etiquetas

Preguntada:

el 12 de Abr. de 2023

Movida:

dpb
el 12 de Abr. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by