Finding and Extracting Instances from a Text File
Afficher commentaires plus anciens
Hi All,
I have a large text file and I need to save all instances of string which comes after a key_name and are betwen specific characters.
For example, there are many instances of strings in the file - could be numebrs, characters, letters - with unknown length, but in the file they all appear after a known key_name phrase and are between known symbols. Example: key_name/':"/This_is_the_string"/
The format always repeat like this, and I want to search for like < key_name/':"/ > and then in an array store whatever comes after the searched phrase up to the next < "/ > character set. There is no space in the text file.
Thank you for your help
UPADTES:
A sample text file is attched. So, I'd like the Matlab script returns an array saying "answer" with three value:
answer = [abc def3ghi JK]
2 commentaires
Matt Gaidica
le 16 Déc 2020
Can you attach a sample file? It will help cover all cases when someone tries to help.
Nima
le 16 Déc 2020
Réponse acceptée
Plus de réponses (1)
Subhadeep Koley
le 16 Déc 2020
Hi, the below code might help.
% Open the file
fid = fopen('sample_text.txt');
% Read the file by character
str = fread(fid, 'uint8=>char');
% Close the file
fclose(fid);
% Search <key_name/':"/> by regural expression matching
[~, endIdx] = regexpi(str', 'key_name/'':"/');
% Find values
result = "";
for ind = 1:length(endIdx)
temp = string(str(endIdx(ind):end)');
result(ind) = strtok(temp, '"/');
end
3 commentaires
Nima
le 16 Déc 2020
Walter Roberson
le 16 Déc 2020
regexp() with 'match' option would have cut out a lot of code. Also, regexp() can work on entire long character vectors, not restricted to line-by-line.
Nima
le 16 Déc 2020
Catégories
En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!