Possible to regexp a file with a for loop using expressions from an array?

조회 수: 5 (최근 30일)
Stephen
Stephen 2019년 7월 4일
답변: Stephen 2019년 7월 5일
I have a text file that I am pulling hex values from using regexp:
returned = string(regexp( filetext, '(?<=xyz address 0x)[0-9a-fA-F]+' , 'match' ));
if ~isempty(returned)
xyzHex = sscanf(returned,'%x');
fprintf ('xyx = %08x \n',xyzHex);
end
(I understand this may be clunky, but I've only just started with MatLab)
What I would like to do is create an array which contains all the expressions I would like to search for, and a single for loop which will iterate though the array, and process the hex value (eg printing). The idea being that adding will only require the addition of the expression to the array.
Is this possible?

답변 (2개)

per isakson
per isakson 2019년 7월 4일
편집: per isakson 2019년 7월 5일
I'm not sure that I fully understand your question. However, try this script %%-section by section
%%
txt = fileread( 'cssm.txt' );
%%
cac = regexp( txt, '(\w+) address 0x([0-9a-fA-F]{8})', 'tokens' );
%% black magic
cac = cat( 1, cac{:} );
sas = cell2struct( cac(:,2), cac(:,1) );
%%
for f = reshape( fields( sas ), 1,[] )
xyzHex = sscanf(sas.(f{1}),'%x');
fprintf( '%s = %x \n', f{1}, xyzHex );
end
where cssm.txt contains
any text xyz address 0x12345678 more text
any text xy1 address 0x12345678AB more text
any text xy2 address 0x90ABCDEF more text
any text xy3 address 0x90abcdef more text
The struct sas
>> sas
sas =
struct with fields:
xyz: '12345678'
xy1: '12345678'
xy2: '90ABCDEF'
xy3: '90abcdef'
>>
The script outputs
xyz = 12345678
xy1 = 12345678
xy2 = 90abcdef
xy3 = 90abcdef
>>

Stephen
Stephen 2019년 7월 5일
Thanks, this looks interesting and I can definitley learn from it.
I'm not certain it wil work in this particular application, as there will be many hex adresses in my file and I only want to pull certain ones, eg. xyz and xy2 but not any others. The ones I want will be added to the array.
I think I have a solution, and if it works I'll share it here, but I found it wasn't working because some of my "xyz" strings have square brackets in them and need to be escaped in the regexp expression, but not in the fprintf :/

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by