Find certain starting and ending characters from a txt file.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Suppose I have a text file. There are right and left brackets([ and ]) in the text. I want to print all those lines that start with [ and end with ]. In my text file the number of [ and ] are not same which means there are some errors. I would also like to print the lines that starts with [ but does not end with ] and vice versa. Finally, I would also like to insert [ or ] where there were no brackets.
0 Kommentare
Antworten (1)
Walter Roberson
am 19 Sep. 2017
I generalized slightly to allow whitespace before the [ or after the ]
S = fileread('YourTextFileName.txt');
balanced = regexp(S, '^\s*\[.*\]\s*$', 'match', 'lineanchors', 'dotexceptnewline')
unbalancedleft = regexp(S, '^\s*\[.*[^\]\s]\s*$', 'match', 'lineanchors', 'dotexceptnewline')
unbalancedright = regexp(S, '^\s*[^\[\s].*\]\s*$', 'match', 'lineanchors', 'dotexceptnewline')
"Finally, I would also like to insert [ or ] where there were no brackets."
That is ambiguous as to whether you want to add in [ at the beginning of lines where it is not present but ] is present at the end of the line, or if instead you want to add in [ at the beginning of lines where the ] is not present at the end of the line -- that is does the "where there were no brackets" refer to the each end of the line, or does it refer to the case where neither [ nor ] was in place.
3 Kommentare
Cedric
am 26 Sep. 2017
because you made a small mistake in the set of elements not to match, you should have
myPattern = '\[[^\[]*';
according to what you just wrote above.
Walter Roberson
am 26 Sep. 2017
To find lines that begin with [ and end with [ with no possibility of leading or trailing spaces, then
result = regexp(S, '^\[.*\[$', 'match', 'lineanchors', 'dotexceptnewline')
If you want to allow for possibly leading or trailing spaces then
result = regexp(S, '^\s*\[.*\[\s*$', 'match', 'lineanchors', 'dotexceptnewline')
These expressions will work whether S is a string or a cell array. However, for a cell array you might get back empty entries corresponding to the places there was no match. For those,
mask = cellfun(@isempty, result);
result(mask) = [];
Siehe auch
Kategorien
Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!