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

조회 수: 26 (최근 30일)
Lucy Cathwell
Lucy Cathwell 2019년 8월 21일
편집: per isakson 2019년 9월 13일
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!

답변 (1개)

the cyclist
the cyclist 2019년 8월 21일
편집: the cyclist 2019년 8월 21일
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
the cyclist
the cyclist 2019년 8월 21일
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 2019년 8월 22일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by