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

26 visualizzazioni (ultimi 30 giorni)
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!

Risposte (1)

the cyclist
the cyclist il 21 Ago 2019
Modificato: the cyclist il 21 Ago 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 Commenti
the cyclist
the cyclist il 21 Ago 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 il 22 Ago 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

Accedi per commentare.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by