Find certain starting and ending characters from a txt file.

2 ビュー (過去 30 日間)
am
am 2017 年 9 月 19 日
コメント済み: Walter Roberson 2017 年 9 月 26 日
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 Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by