Find strings within other strings then pull data from that point

조회 수: 3 (최근 30일)
A-Rod
A-Rod 2024년 8월 19일
댓글: Voss 2024년 8월 20일
dear collegaes, please let me ask your help to find a solution for my data analisys.
I have a P0300.txt file that contains a long strip.
here is a portion of P0300.txt:
59 04 03 01 00 65 01 3E 51 09 00 00 51 1C 00 E1
I need to find sets of data, sets could be 2 or 4 digits.
lets say I need to find 01 3E
DATA = regexp(fileread('P0300.txt'), '\r?\n', 'split')';
>> A = string(DATA);
>> B = strfind(A,'01 3E');
B gives me the position where 01 3E is, in this case B = 19
after this I need to extract the 6 digits on the rigth 51 09 00 <-- this values can change depend on test conditions
Any idea on how can I do that?
your feedback will be highly appreciated

채택된 답변

Voss
Voss 2024년 8월 19일
filename = 'P0300.txt';
to_find = '01 3E';
str = fileread(filename);
pat = strjoin(repmat({'[\dA-F]{2}'},1,3),' ');
C = regexp(str,[to_find ' (' pat ')'],'tokens');
C = [C{:}]
C = 1x1 cell array
{'51 09 00'}
  댓글 수: 10
A-Rod
A-Rod 2024년 8월 20일
이동: Voss 2024년 8월 20일
it saved my day!! you're the best thanks a lot

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

추가 답변 (2개)

Animesh
Animesh 2024년 8월 19일
편집: Animesh 2024년 8월 19일
Hey @A-Rod,
To extract 6 digits following a specific pattern in your text file, you can utilize MATLAB's string manupilation functions such as 'regexp'.
Here is a sample MATLAB script to achieve the same:
fileContent = fileread('P0300.txt');
pattern = '01 3E';
% Use regular expression to find the pattern and extract the following 6 digits
expression = [pattern, '\s+([\dA-F]{2}\s+[\dA-F]{2}\s+[\dA-F]{2})'];
match = regexp(fileContent, expression, 'tokens');
% Check if any match is found
if ~isempty(match)
% Extract the first match (if multiple matches are found)
extractedDigits = match{1}{1};
fprintf('Extracted digits: %s\n', extractedDigits);
else
fprintf('Pattern not found in the file.\n');
end
Extracted digits: 51 09 00
You can refer the following MathWorks documentation for more information:
  댓글 수: 1
A-Rod
A-Rod 2024년 8월 19일
Thank you for taking time to asnwer my question, this code does the job.

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


Matt J
Matt J 2024년 8월 19일
편집: Matt J 2024년 8월 19일
fileContent = fileread('P0300.txt');
prefix="01 3E";
e=" "+digitsPattern(2);
pattern = prefix+e+e+e;
matches = extractAfter( extract(fileContent,pattern), prefix);
  댓글 수: 1
A-Rod
A-Rod 2024년 8월 19일
I'm using version 2019 digitsPattern is not available. thanks a lot for your feedback

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

카테고리

Help CenterFile Exchange에서 Language Support에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by