Read data from string

1 visualización (últimos 30 días)
Artyom
Artyom el 7 de Ag. de 2013
I have string line:
x='abc123(xyz456)'
How to read information only in brackets, to have result:
y='xyz456'.

Respuesta aceptada

Evan
Evan el 7 de Ag. de 2013
Editada: Evan el 7 de Ag. de 2013
>> x='abc123(xyz456)';
>> regexp(x,'(?<=\().+(?=\))','match')
ans =
'xyz456'
This command uses regexp and, specifically, lookaround assertions. It's basically saying, if you find a group of characters, look behind to see if there is an "open parenthesis" character and look ahead to see if there is a "close parenthesis" character. If so, return all the characters between them.
  6 comentarios
per isakson
per isakson el 7 de Ag. de 2013
Editada: per isakson el 7 de Ag. de 2013
Surprise!
regexp('_A_A-', '(?<=_)[^_]+?(?=-)', 'match' )
ans =
'A'
Thus, doc should say something like
Lazy expression: match as few characters as necessary **downstream**.
Cedric
Cedric el 7 de Ag. de 2013
Editada: Cedric el 8 de Ag. de 2013
Yep, in other words, it stops when it matches the last part of the pattern for the first time (lazy), but it doesn't pull back the starting point (the tail? ;-)) to minimize the match (not that lazy finally, or really really lazy in fact). Thankfully, you see/understand this once and you never forget it!

Iniciar sesión para comentar.

Más respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 7 de Ag. de 2013
y=regexp(x,'(?<=\()[\w]+(?=\))','match')
  1 comentario
Azzi Abdelmalek
Azzi Abdelmalek el 7 de Ag. de 2013
%or
x=x='abc123 (xyz 45_6) ddd (rtr)ccc'
y=regexp(x,'\(([\w\s]+)\)','tokens');
celldisp(y)

Iniciar sesión para comentar.


Jan
Jan el 7 de Ag. de 2013
x = 'abc123(xyz456)';
ini = strfind(x, '(');
fin = strfind(x, ')');
key = x(ini(1) + 1:fin(1) - 1);

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by