Nick Kahn
Nick Kahn

Reputation: 20078

Split separates strings and ignore/remove other delimited string

I'm reading a comma-delimited list of strings from a config file. I need to check the following steps

1) check to see if the string has `[`, if it is then remove or ignore...
2) split `,` `-` //which i am doing below...

Here is what I able to do so far;

string mediaString = "Cnn-[news],msnbc";

string[] split = mediaString.Split(new Char[] { ',', '-' }); //gets me the bracket

what I want is to ignore/remove the string which is in the brackets so the end result should be like this:

mediaString = 
                Cnn
                msnbc

Upvotes: 0

Views: 2013

Answers (3)

Colin Young
Colin Young

Reputation: 3058

Using Linq:

mediaString.Split(new Char[] { ',', '-' }).Where(val => !val.Contains('[')

You can make the test (val.Contains(...)) as sophisticated as you like (e.g. starts and ends with, regular expression, specific values, call an object provided via a DI framework if you want to get all enterprisey).

Upvotes: 2

yelman
yelman

Reputation: 44

Without using LINQ or regex: Split your string as you are doing now. Create a data structure of string type for example: List. Run over the results array and for each entry check it contains the specified character, if it doesn't add it to the List. In the end you should have a List with the required result.

This The regex solution is far more elegant but if you cannot use reg ex this one should do it

Upvotes: 0

Mzf
Mzf

Reputation: 5260

Use Regex replace to clean your string

        string str = @"Cnn-[news],msnbc";

        Regex regex = new Regex(@"\[.*\]");
        string cleanStr = regex.Replace(str, "");
        string[] split = cleanStr.Split(new Char[] { ',', '-' });

Upvotes: 1

Related Questions