Find certain starting and ending characters from a txt file.
2 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Walter Roberson
on 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 Comments
Cedric
on 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
on 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) = [];
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!