Find certain starting and ending characters from a txt file.

2 次查看(过去 30 天)
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.

回答(1 个)

Walter Roberson
Walter Roberson 2017-9-19
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 个评论
Cedric
Cedric 2017-9-26
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
Walter Roberson 2017-9-26
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) = [];

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by