how to use regexp to get the last characters of a line

24 visualizaciones (últimos 30 días)
Lucy Cathwell
Lucy Cathwell el 21 de Ag. de 2019
Editada: per isakson el 13 de Sept. de 2019
file = uigetfile('*.txt','Select the text file to parse');
fid=fopen(file)
text=fileread(file)
expr='[^\n]*Machine Name=[^\n]*';
matches=regexp(text, expr,'match');
disp(matches)
I have a really long complicated text file that I want to parse. It is really long and is a list of lines. There are no comma delimiters, but the machine name that I am looking for is always at the end of the line ... like
121212323 : Machine Name = roboDog
121222323 : Machine IOS = Android
The code above was my attempt to desplay the lines which contained the keyword. It wouldn't work, but I would ideally like each Machine Name to be stored in a vector like machineName={'roboDog' ; 'roboCat'}
Thanks!

Respuestas (1)

the cyclist
the cyclist el 21 de Ag. de 2019
Editada: the cyclist el 21 de Ag. de 2019
Your definition of expr does not have a space between "Machine Name" and the equals sign, but your text example does. When I put that space in, it found the match.
  8 comentarios
the cyclist
the cyclist el 21 de Ag. de 2019
With the attached text file, and this code:
fid=fopen('machine.txt');
text=fileread('machine.txt')
expr='(?<=Name = )\w*';
matches=regexp(text, expr,'match')
I get a 1x2 cell array:
matches =
1×2 cell array
{'roboDog'} {'roboCat'}
Walter Roberson
Walter Roberson el 22 de Ag. de 2019
I suspect that machine names might not strictly match \w as that does not include '-' for example. I suggest
expr = '(?<=Name =\s*).*?(?=\s*)$';
matches = regexp(text, expr, 'match', 'lineanchors', 'dotexceptnewline')
This strips out leading and trailing whitespace and accepts anything between

Iniciar sesión para comentar.

Categorías

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

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by