Suppose that I have a string str
. str
contains headings -- which are written in commented lines -- and data. For example:
str = "# Heading 1
# Heading 2
@ Heading 3
@ Heading 4
Data 1
Data 2
Data 3";
where #
and @
denote commented lines.
Now, I would like to write a function removeComments
to remove all lines in str
that are commented. That is, I would like to remove all lines in str
that start with the character #
or the character @
.
I have come up with one way to do this, I think. My procedure is to first split str
into lines using StringSplit
with the "\n"
delimiter; then use DeleteCases
to delete all lines in that list which begin with either #
or @
; and, finally, convert the list back to a string using Riffle
and StringJoin
. So, I have the following:
removeComments[str_String] := Module[{result},
result = StringSplit[str, "\n"];
result =
DeleteCases[
result, _?(StringMatchQ[#, ("#" ~~ ___) | ("@" ~~ ___)] &)];
result = StringJoin[Riffle[result, "\n"]];
result
]
removeComments[str]
which gives the following correct output (a string):
Data 1
Data 2
Data 3
However, now suppose that one of my data items (for example, a single space in front of Data 2
) has one or more leading spaces:
str = "# Heading 1
# Heading 2
@ Heading 3
@ Heading 4
Data 1
Data 2
Data 3";
removeComments[str]
In this case, I get the incorrect output:
Data 1
Data 3
That is, Data 2
is omitted altogether. Something is clearly wrong with my approach, but I haven't been able to find my mistake (although it is probably obvious). Could you please help me find what is wrong? Thanks for your time.
Data 2
. $\endgroup$