Remove text in between delimiters in a string that can contains the delimeter

Viewed 71

I'm trying to filter some text/data out of a string.

My intention is to eventually get two strings as a result, namely the original text without the texts between the delimiters (and without the delimiter characters) and a new string consisting of all characters between all delimiters. The problem is that the data between brackets can contain anything, including "[", "]" and "," as well. So it is possible there is a single opening bracket without a closing bracket can be defined between the delimiters

here is an example: Here is some input text. The delimiter characters are '[' and ']', so everything between (including the delimiter characters) should be deleted out of the input string. The data between the surrounding brackets (brackets excluded) should be saved. All the strings between the delimiters should be concatenated to one big string.

String input ="{[bra],pro,{[ckets[]]},ent[,HDR]}";

Expected results

String filteredText = "{,pro,{},ent}"; //The original text - the delimiters (surrounding brackets) - everything between the delimiters. 

String dataText = "brackets[],HDR"; //The text of all in-between delimiters without the surrounding brackets 

I tried to loop manually over every character inside the whole string and try to find a start point and an endpoint, to get the data between the brackets manually. Something like this:

[ = openCloseBracket +1

] = openCloseBracket -1

This way we can determine a startIndex and a endIndex. This should only work when all open brackets containing a closing bracket. Since the bracket data can contain brackets as well, there isn't a clear start and stop condition, so this won't work. This is why a RegEx function for example "<.>", "<.?>" or "(\<.\>)| (".")|('.')|(\(.\))" won't work as expected to filter the brackets away.

How can i get the filtered text and the characters that are deleted from the text (as one charArray/string)(without the outer delimiter/brackets)? Is there maybe some better, simpler way to loop manually over the whole text?

1 Answers

This should work for a manual loop:

string input = "{[bra],pro,{[ckets[]]},ent[,HDR]}";
StringBuilder filtered = new StringBuilder();
StringBuilder data = new StringBuilder();

int bracketCount = 0;

foreach (char c in input)
{
    if (bracketCount > 0)
    {
        if (c == '[')
            bracketCount++;
        else if (c == ']')
            bracketCount--;

        if (bracketCount > 0)
            data.Append(c);
    }
    else
    {
        if (c == '[')
            bracketCount++;
        else if (c == ']')
            bracketCount--;
        else
            filtered.Append(c);
    }
}

Console.WriteLine(filtered);
Console.WriteLine(data);

Unless you're sure all of the inputs are valid, you'll probably want to add some error checking to the loop. Make sure bracket matches are correct, etc.

Related